/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.sql.internal

import org.intellij.lang.annotations.Language
import org.jetbrains.exposed.v1.core.ColumnType
import org.jetbrains.exposed.v1.core.Expression
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.statements.StatementType
import org.jetbrains.exposed.v1.dao.IntEntity
import org.jetbrains.exposed.v1.dao.IntEntityClass
import org.jetbrains.exposed.v1.jdbc.Database
import org.jetbrains.exposed.v1.jdbc.JdbcTransaction
import org.jetbrains.exposed.v1.jdbc.statements.jdbc.JdbcResult
import org.jetbrains.exposed.v1.jdbc.transactions.TransactionManager
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import java.io.File
import java.util.*

object KotlinDatabase {
    var db: Database? = null

    fun ensureConnected() {
        if (db != null) return

        val file = File(System.getProperty("user.home"), "mysql.properties")

        val properties = Properties()
        properties.load(file.inputStream())

        val host = properties.getProperty("host")
        val port = properties.getProperty("port")
        val database = properties.getProperty("database")
        val username = properties.getProperty("user")
        val password = properties.getProperty("password")

        db = Database.connect(
            "jdbc:mysql://$host:$port/$database",
            driver = "com.mysql.cj.jdbc.Driver",
            user = username,
            password = password
        )
    }

    fun close() {
        db?.connector()?.close()
        TransactionManager.defaultDatabase?.let { TransactionManager.closeAndUnregister(it) }
        db = null
    }
}

fun <T> useDb(statement: JdbcTransaction.() -> T): T {
    KotlinDatabase.ensureConnected()
    return TransactionManager.currentOrNull()?.statement()
        ?: transaction(KotlinDatabase.db) {
            statement()
        }
}

fun <T : IntEntity> IntEntityClass<T>.fromSql(
    @Language("MySQL") stmt: String,
    args: List<Pair<ColumnType<*>, Any?>>,
    fieldIndex: Map<Expression<*>, Int>
): List<T> =
    useDb {
        exec(stmt, explicitStatementType = StatementType.SELECT, args = args) {
            val list = mutableListOf<T>()
            while (it.next()) {
                list.add(wrapRow(ResultRow.create(JdbcResult(it), fieldIndex)))
            }
            list
        }
            ?: listOf()
    }