package com.jaytux.simd

import com.jaytux.simd.data.Database
import com.jaytux.simd.data.Loader
import com.jaytux.simd.server.configureFallback
import com.jaytux.simd.server.configureHTTP
import com.jaytux.simd.server.configureRouting
import com.jaytux.simd.server.configureSerialization
import io.ktor.server.application.*
import io.ktor.server.netty.*
import kotlinx.coroutines.runBlocking

fun main(args: Array<String>) {
    println("Arguments (${args.size}): [${args.joinToString(", ")}]")

    if(args.size >= 3 && args[0] == "-reload") {
        val xmlFile = args[1]
        val jsonFile = args[2]
        val force = args.size > 3 && args[3] == "-force"
        dbSetup(xmlFile, jsonFile, force)
    }
    else if(args.size >= 1 && args[0] == "-h") {
        println("Usage: -reload <xmlFile> <jsonFile>             (to reload the database)")
        println("       -reload <xmlFile> <jsonFile> -force      (to force reload the database; overwriting data even if the database has newer data)")
        println("       -h                                       (to show this help message)")
        println("       (no arguments)                           (to start the server)")
    }
    else {
        EngineMain.main(args)
    }
}

fun dbSetup(xmlFile: String, jsonFile: String, force: Boolean = false) {
    runBlocking {
        val xml = Loader.loadXml(xmlFile)
        val perf = Loader.loadJson(jsonFile)

        val current = Loader.DatedVersion.fromPrefs()
        if(force || (xml.version.version isNewerThan current.version)) {
            Database.reset()
            Loader.importToDb(xml, perf)
        }
        if(!(xml.version.version isNewerThan current.version)) {
            System.err.println("The XML file (${xml.version}) is not more up-to-date than the database ($current). Use -force to force importing.")
        }
    }
}

fun Application.module() {
    Database.db
    configureSerialization()
    configureHTTP()
    configureRouting()

    configureFallback()
}