package pw.hamzantal.vagueenchants.enchantments


import com.google.common.collect.Maps
import org.bukkit.enchantments.Enchantment
import org.bukkit.enchantments.EnchantmentTarget
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import pw.hamzantal.vagueenchants.*
import kotlin.IllegalStateException as ISE

abstract class CustomEnchant(id: Int, val config: EnchantmentInfo, private val theName: String) : Enchantment(id) {

	fun customEnchant(item: ItemStack, newLevel: Int = 1): Boolean {
		val lor = if (item.itemMeta.hasLore()) item.itemMeta.lore else mutableListOf()
		val oldLevel = if (this in item.enchantments) item.enchantments[this]!! else -1
		val index = lor.indexOf(loreString(oldLevel))

		if (newLevel <= 0) {
			if (this in item.enchantments) {
				item.itemMeta = item.itemMeta.apply {
					lore = lor.apply { removeAt(index) }
					removeEnchant(this@CustomEnchant)
				}
				if (index == -1) throw ISE("Has $name enchantment without enchantment lore.")
			}
			return false
		}

		if (this in item.enchantments) {
			item.removeEnchantment(this)
			if (index == -1) throw ISE("Has $name enchantment without enchantment lore.")
			lor[index] = loreString(newLevel)
		} else lor.add(loreString(newLevel))

		item.itemMeta = item.itemMeta.also { it.lore = lor }
		item.addUnsafeEnchantment(this, newLevel)

		return newLevel > 0
	}

	private val map = Maps.newTreeMap<Int, String>().apply {
		this[1000] = "M"
		this[900] = "CM"
		this[500] = "D"
		this[400] = "CD"
		this[100] = "C"
		this[90] = "XC"
		this[50] = "L"
		this[40] = "XL"
		this[10] = "X"
		this[9] = "IX"
		this[5] = "V"
		this[4] = "IV"
		this[1] = "I"
	}

	fun loreLevel(level: Int): String {

		val l = map.floorKey(level) ?: return "0"
		return if (level == l) map[level]!! else map[l].toString() + loreLevel(level - l)
	}

	abstract fun inspect(p: Player, level: Int)
	abstract fun loreString(level: Int): String

	override fun isTreasure() = false
	override fun conflictsWith(p0: Enchantment) = false
	override fun getStartLevel() = 1
	override fun getMaxLevel() = config.max
	override fun getName() = theName
	override fun canEnchantItem(i: ItemStack) = i.type in listOf(
		ToolUtils.pickaxes, ToolUtils.axes, ToolUtils.shovels
	).flatten()

	override fun getItemTarget() = EnchantmentTarget.TOOL
}