package xyz.etztech.stonks.statisticsimporter

import com.beust.klaxon.*
import com.beust.klaxon.Klaxon
import java.io.File
import java.time.Instant
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.`java-time`.timestamp
import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import xyz.etztech.stonks.dsl.Statistics

object StatisticsImporter {
    init {}

    private val klaxon = Klaxon()

    fun importStatistics(folder: String, database: Database) {
        println("Importing new statistics...")
        File(folder).listFiles().forEach { readFile(it, database) }
        println("Updating live statistics table...")
        updateLiveStatistics(database)
    }

    fun readFile(file: File, database: Database) {
        val statsFile = StatsFile.fromJson(file.readText())
        val playerId = file.nameWithoutExtension

        transaction(database) {
            val maxExpr = Statistics.value.max()

            val playerStats = emptyMap<String, MutableMap<String, Long>>().toMutableMap()

            Statistics.slice(Statistics.type, Statistics.name, maxExpr)
                    .select { Statistics.playerId.eq(playerId) }
                    .groupBy(Statistics.type, Statistics.name)
                    .forEach {
                        if (playerStats.containsKey(it[Statistics.type])) {
                            playerStats[it[Statistics.type]]?.put(
                                    it[Statistics.name], it[maxExpr]!!)
                        } else {
                            playerStats.put(
                                    it[Statistics.type],
                                    mapOf<String, Long>(it[Statistics.name] to it[maxExpr]!!)
                                            .toMutableMap())
                        }
                    }

            statsFile?.stats?.forEach { type, stats ->
                stats.forEach { name, value ->
                    if (playerStats.get(type)?.get(name) != value) {
                        Statistics.insert {
                            it[Statistics.playerId] = playerId
                            it[Statistics.type] = type
                            it[Statistics.name] = name
                            it[Statistics.timestamp] = Instant.now() as Instant
                            it[Statistics.value] = value
                        }
                    }
                }
            }
        }
    }

    fun updateLiveStatistics(database: Database) {
        transaction(database) {
            TransactionManager.current()
                    .exec(
                            """
                        MERGE INTO LIVESTATISTICS AS T USING (
                            SELECT
                                STATISTICS."Type",
                                STATISTICS."Name",
                                STATISTICS."PlayerId",
                                STATISTICS."Value",
                                (RANK () OVER (PARTITION BY STATISTICS."Type", STATISTICS."Name" ORDER BY STATISTICS."Value" DESC)) AS "Rank"
                            FROM
                                STATISTICS
                                JOIN (
                                    SELECT
                                        "Type",
                                        "Name",
                                        "PlayerId",
                                        MAX("Timestamp") AS "MaxTimestamp",
                                    FROM STATISTICS
                                    GROUP BY 
                                        "Type",
                                        "Name",
                                        "PlayerId"
                                ) MAX_TIMESTAMPS
                                ON
                                    STATISTICS."Type" = MAX_TIMESTAMPS."Type"
                                    AND STATISTICS."Name" = MAX_TIMESTAMPS."Name"
                                    AND STATISTICS."PlayerId" = MAX_TIMESTAMPS."PlayerId"
                                    AND STATISTICS."Timestamp" = MAX_TIMESTAMPS."MaxTimestamp"
                        ) AS S
                        ON (T."Type" = S."Type" AND T."Name" = S."Name" AND T."PlayerId" = S."PlayerId")
                        
                        WHEN MATCHED AND (S."Value" <> T."Value" OR S."Rank" <> T."Rank")THEN
                            UPDATE SET T."Value" = S."Value", T."Rank" = S."Rank"
                        WHEN NOT MATCHED THEN
                            INSERT VALUES (S."PlayerId", S."Type", S."Name", S."Value", S."Rank")
                    """.trimIndent())
        }
    }

    data class StatsFile(val stats: Map<String, Map<String, Long>>) {
        companion object {
            public fun fromJson(json: String) = klaxon.parse<StatsFile>(json)
        }
    }
}
