package org.server_info.MOTD

import MOTDGuiHandler
import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.plugin.java.JavaPlugin
import java.io.File
import java.util.*

class MOTD : JavaPlugin() {

    private val quotes = ArrayList<QuoteItem>()
    private var currentQuoteIndex = 0
    private var quoteTaskId = -1

    data class QuoteItem(val text: String, val color: String)

    override fun onEnable() {
        // Create default config if it doesn't exist
        saveDefaultConfig()

        // Initialize quotes system
        initializeQuotes()

        // Register command executor
        getCommand("motd")?.setExecutor(MOTDCommand(this))

        // Register GUI handler
        val guiHandler = MOTDGuiHandler(this)
        server.pluginManager.registerEvents(guiHandler, this)

        logger.info("MOTD Plugin enabled!")
    }

    override fun onDisable() {
        // Cancel task if running
        if (quoteTaskId != -1) {
            Bukkit.getScheduler().cancelTask(quoteTaskId)
        }

        // Save quotes on shutdown
        saveQuotes()

        logger.info("MOTD Plugin disabled!")
    }

    // Initialize quotes system
    fun initializeQuotes() {
        // Make sure the data folder exists
        if (!dataFolder.exists()) {
            dataFolder.mkdirs()
        }

        // Load quotes from config
        loadQuotes()

        // Start the task to change quotes
        startQuoteTask()
    }

    // Save quotes to config
    fun saveQuotes() {
        try {
            val config = YamlConfiguration()
            val quotesList = ArrayList<Map<String, String>>()

            for (quote in quotes) {
                val quoteMap = HashMap<String, String>()
                quoteMap["text"] = quote.text
                quoteMap["color"] = quote.color.replace('§', '&') // Store with & instead of § for readability
                quotesList.add(quoteMap)
            }

            config.set("quotes", quotesList)

            // Save to file
            val file = File(dataFolder, "quotes.yml")
            config.save(file)

            // Update the main config to point to this file
            val mainConfig = YamlConfiguration.loadConfiguration(File(dataFolder, "config.yml"))
            mainConfig.set("quotes_file", "quotes.yml")
            mainConfig.save(File(dataFolder, "config.yml"))

            logger.info("Saved ${quotes.size} quotes to quotes.yml")
        } catch (e: Exception) {
            logger.severe("Failed to save quotes: ${e.message}")
            e.printStackTrace()
        }
    }

    // Load quotes from config
    fun loadQuotes() {
        try {
            val configFile = File(dataFolder, "config.yml")
            if (!configFile.exists()) {
                saveDefaultConfig()
            }

            val config = YamlConfiguration.loadConfiguration(configFile)
            val quotesFile = config.getString("quotes_file", "quotes.yml")

            val quotesConfig = File(dataFolder, quotesFile)
            if (!quotesConfig.exists()) {
                // Create default quotes file if it doesn't exist
                val defaultQuotes = ArrayList<Map<String, String>>()
                val defaultQuote = HashMap<String, String>()
                defaultQuote["text"] = "Welcome to our server!"
                defaultQuote["color"] = "&e"
                defaultQuotes.add(defaultQuote)

                val tempConfig = YamlConfiguration()
                tempConfig.set("quotes", defaultQuotes)
                tempConfig.save(quotesConfig)
            }

            // Load quotes
            val quotesYaml = YamlConfiguration.loadConfiguration(quotesConfig)
            val quotesList = quotesYaml.getMapList("quotes")

            quotes.clear()

            for (quoteMap in quotesList) {
                @Suppress("UNCHECKED_CAST")
                val map = quoteMap as? Map<String, String> ?: continue
                val text = map["text"] ?: continue
                val color = (map["color"] ?: "&f").replace('&', '§')
                quotes.add(QuoteItem(text, color))
            }

            logger.info("Loaded ${quotes.size} quotes from $quotesFile")
        } catch (e: Exception) {
            logger.severe("Failed to load quotes: ${e.message}")
            e.printStackTrace()

            // Create a default quote if loading fails
            if (quotes.isEmpty()) {
                quotes.add(QuoteItem("Welcome to our server!", "§e"))
            }
        }
    }

    // Start the task to change quotes periodically
    fun startQuoteTask() {
        // Cancel existing task if running
        if (quoteTaskId != -1) {
            Bukkit.getScheduler().cancelTask(quoteTaskId)
            quoteTaskId = -1
        }

        // Get update interval from config (in minutes)
        val intervalMinutes = config.getInt("update_interval", 15)
        val intervalTicks = intervalMinutes * 60 * 20L // Convert to ticks

        if (intervalMinutes <= 0) {
            logger.info("Automatic MOTD updates disabled (interval set to 0)")
            return
        }

        quoteTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(this, {
            updateServerMOTD()
        }, intervalTicks, intervalTicks)

        logger.info("MOTD will update every $intervalMinutes minutes")
    }

    // Update the server MOTD with the next quote
    fun updateServerMOTD() {
        if (quotes.isEmpty()) {
            logger.warning("No quotes available for MOTD")
            return
        }

        // Select next quote or random based on config
        val useRandom = config.getBoolean("random_quotes", true)
        if (useRandom) {
            currentQuoteIndex = Random().nextInt(quotes.size)
        } else {
            currentQuoteIndex = (currentQuoteIndex + 1) % quotes.size
        }

        val quote = quotes[currentQuoteIndex]

        // Get the static part of the MOTD from config
        val staticPart = ChatColor.translateAlternateColorCodes('&',
            config.getString("static_motd", "&6Crossplay Java & Bedrock") ?: "&6Crossplay Java & Bedrock!")

        // Combine static part with quote
        val fullMotd = "$staticPart\n${quote.color}${quote.text}"

        try {
            // Update the server MOTD
            val server = Bukkit.getServer()
            val serverClass = server.javaClass

            // Attempt to access Spigot/Paper setMotd method first
            try {
                val motdMethod = serverClass.getMethod("setMotd", String::class.java)
                motdMethod.invoke(server, fullMotd)
                logger.info("Updated MOTD: $fullMotd")
                return
            } catch (e: NoSuchMethodException) {
                // Method not found, try other ways
            }

            // Try to find the method in a different way for different server implementations
            for (method in serverClass.methods) {
                if (method.name.equals("setMotd", ignoreCase = true) && method.parameterCount == 1) {
                    method.invoke(server, fullMotd)
                    logger.info("Updated MOTD: $fullMotd")
                    return
                }
            }

            // If we get here, warn that the MOTD couldn't be updated
            logger.warning("Could not update server MOTD. Server implementation not supported.")

        } catch (e: Exception) {
            logger.severe("Error updating server MOTD: ${e.message}")
            e.printStackTrace()
        }
    }

    // Get the current list of quotes
    fun getCurrentQuotes(): List<QuoteItem> {
        return quotes.toList()
    }

    // Add a new quote
    fun addQuote(text: String, color: String): Boolean {
        if (text.isBlank()) return false

        quotes.add(QuoteItem(text, color))
        return true
    }

    // Remove a quote by index
    fun removeQuote(index: Int): Boolean {
        if (index < 0 || index >= quotes.size) return false

        quotes.removeAt(index)
        return true
    }

    // Edit an existing quote
    fun editQuote(index: Int, text: String, color: String): Boolean {
        if (index < 0 || index >= quotes.size || text.isBlank()) return false

        quotes[index] = QuoteItem(text, color)
        return true
    }

    // Reload quotes from config
    fun reloadQuotes() {
        loadQuotes()
        updateServerMOTD() // Update the MOTD immediately
    }
}