package de.steamwar.commands.database

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.CliktError
import com.github.ajalt.clikt.core.requireObject
import com.github.ajalt.mordant.rendering.TextColors
import com.github.ajalt.mordant.rendering.TextStyles
import de.steamwar.db.Database
import de.steamwar.db.execute
import de.steamwar.db.executeScript
import de.steamwar.db.useDb
import java.io.File

class ResetCommand : CliktCommand() {
    val db by requireObject<Database>()

    override fun run() =
        useDb {
            val schemaFile = File("/var/Schema.sql")
            if (!schemaFile.exists()) {
                throw CliktError("Schema file not found!")
            }

            val schema = schemaFile.readText()

            execute("SET FOREIGN_KEY_CHECKS=0;") { }

            val databaseObjects = execute("SHOW FULL TABLES;") { it.getString(1) to it.getString(2) }
            for (view in databaseObjects.filter { it.second == "VIEW" }.map { it.first }) {
                execute("DROP VIEW IF EXISTS `${view.replace("`", "``")}`;") { }
            }
            for (table in databaseObjects.filter { it.second == "BASE TABLE" }.map { it.first }) {
                execute("DROP TABLE IF EXISTS `${table.replace("`", "``")}`;") { }
            }

            executeScript(schema)

            val seed = javaClass.getResource("/db/reset-seed.sql")
                ?: throw CliktError("Reset seed file not found!")

            executeScript(seed.readText())

            execute("SET FOREIGN_KEY_CHECKS=1;") { }

            echo(TextColors.brightGreen(TextStyles.bold("Database reset!")))
        }
}
