package ru.dbotthepony.kstarbound

import org.apache.logging.log4j.LogManager
import org.lwjgl.Version
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
import ru.dbotthepony.kstarbound.client.StarboundClient
import ru.dbotthepony.kstarbound.server.IntegratedStarboundServer
import java.io.File
import java.net.InetSocketAddress
import java.util.concurrent.Callable
import kotlin.system.exitProcess

private val LOGGER = LogManager.getLogger()

@Command(
	name = "client",
	mixinStandardHelpOptions = true,
	description = ["Launches game client"]
)
class StartClientCommand : Callable<Int> {
	@Option(names = ["-d", "--data"], description = ["Game folder where Starbound is installed.", "Defaults to working directory."])
	var dataFolder: String = "./"

	@Option(names = ["-s", "--storage"], description = ["Location where to store game files.", "Defaults to game's 'storage' subfolder"])
	var storageFolder: String? = null

	override fun call(): Int {
		val data = File(dataFolder)

		if (!data.exists()) {
			LOGGER.fatal("No such file ${data.absolutePath}")
			return 1
		}

		val file = File("${dataFolder}/assets/packed.pak")

		if (!file.exists()) {
			LOGGER.fatal("No such file ${file.absolutePath}")
			return 1
		}

		Starbound.addArchive(file)

		/*for (f in File("J:\\Steam\\steamapps\\workshop\\content\\211820").listFiles()!!) {
			for (f2 in f.listFiles()!!) {
				if (f2.isFile) {
					Starbound.addArchive(f2)
				}
			}
		}*/

		LOGGER.info("Running LWJGL ${Version.getVersion()}")

		val client = StarboundClient()

		Starbound.initializeGame().thenApply {
			val server = IntegratedStarboundServer(client, if (storageFolder == null) File(data, "storage") else File(storageFolder!!))
			server.channels.createChannel(InetSocketAddress(21060))
		}.exceptionally { LOGGER.error("what", it); null }

		return 0
	}
}

fun main(vararg args: String) {
	val result = CommandLine(StartClientCommand()).execute(*args)

	if (result != 0) {
		exitProcess(result)
	}
}
