/*
 *   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.tntleague.config

import de.steamwar.message.SubMessage
import de.steamwar.sql.Event
import de.steamwar.sql.EventFight
import de.steamwar.sql.Team
import de.steamwar.tntleague.plugin
import org.bukkit.Material
import org.bukkit.configuration.ConfigurationSection
import org.bukkit.configuration.file.FileConfiguration
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.meta.Damageable
import org.bukkit.inventory.meta.ItemMeta
import java.util.*

data class TNTLeagueConfig(
    val startDelay: Int = 10,
    val gameTime: Int = 60 * 20,

    val prices: Map<Material, Price>,

    val blueLeader: UUID? = System.getProperty("blueLeader")?.let { UUID.fromString(it) },
    val redLeader: UUID? = System.getProperty("redLeader")?.let { UUID.fromString(it) },

    val eventFightId: Int? = System.getProperty("fightID")?.toInt()
) {
    lateinit var eventFight: EventFight
    lateinit var event: Event
    lateinit var eventTeamBlue: Team
    lateinit var eventTeamRed: Team

    val blueTeam: TeamConfig
    val redTeam: TeamConfig

    init {
        if (eventFightId != null && eventFightId > 0) {
            eventFight = EventFight.byId(eventFightId)
                ?: throw IllegalArgumentException("EventFight with ID $eventFightId not found")

            event = Event.byId(eventFight.eventID)!!

            eventTeamBlue = Team.byId(eventFight.teamBlue)
            eventTeamRed = Team.byId(eventFight.teamRed)

            blueTeam = TeamConfig(TNTLeagueWorldConfig.blueTeam, SubMessage("PLAIN_STRING", "§${eventTeamBlue.teamColor}${eventTeamBlue.teamName}"), eventTeamBlue.teamColor[0])
            redTeam = TeamConfig(TNTLeagueWorldConfig.redTeam, SubMessage("PLAIN_STRING", "§${eventTeamRed.teamColor}${eventTeamRed.teamName}"), eventTeamRed.teamColor[0])
        } else {
            blueTeam = TeamConfig(TNTLeagueWorldConfig.blueTeam, SubMessage("BLUE"), '9')
            redTeam = TeamConfig(TNTLeagueWorldConfig.redTeam, SubMessage("RED"), 'c')
        }
    }

    companion object {
        val config: TNTLeagueConfig by lazy { loadConfig(plugin.config) }

        private fun loadConfig(config: FileConfiguration): TNTLeagueConfig {
            return TNTLeagueConfig(config.getInt("startDelay"), config.getInt("gameTime"), loadPrices(config.getConfigurationSection("prices")!!))
        }

        private fun loadPrices(config: ConfigurationSection): Map<Material, Price> {
            return config.getKeys(false).associateWith {
                Price(
                    config.getInt("$it.amount"),
                    config.getInt("$it.price"),
                    config.getString("$it.category")?.let { s -> categoryFromString[s] }
                        ?: ItemCategory.REDSTONE,
                    config.getInt("$it.pinned", -1),
                    config.getStringList("$it.extras").map { s -> extrasFromString[s]!! }.toSet()
                )
            }.mapKeys {
                Material.getMaterial(it.key)
                    ?: Material.BARRIER
            }
        }

        fun isEvent() =
            (config.eventFightId
                ?: 0) > 0
    }

    data class Price(
        val amount: Int,
        val price: Int,
        val category: ItemCategory,
        val pinned: Int,
        val extras: Set<ItemExtra>
    )

    enum class ItemCategory {
        REDSTONE,
        BLOCKS,
        TOOLS,
        ANGLES;
    }

    enum class ItemExtra(val func: (item: ItemMeta) -> Unit) {
        ONESHOT({
            if (it is Damageable) {
                it.damage = 384
            }
        }),
        FLAME({
            it.addEnchant(Enchantment.FLAME, 1, false)
        }),
        UNBREAKING({
            it.addEnchant(Enchantment.UNBREAKING, 1, false)
        }),
        EFFICIENCY({
            it.addEnchant(Enchantment.EFFICIENCY, 1, false)
        })
    }
}

val categoryFromString = TNTLeagueConfig.ItemCategory.entries.associateBy { it.name.lowercase() }
val extrasFromString = TNTLeagueConfig.ItemExtra.entries.associateBy { it.name.lowercase() }
