package pw.hamzantal.vagueenchants

import me.clip.placeholderapi.expansion.PlaceholderExpansion
import org.bukkit.enchantments.Enchantment
import org.bukkit.entity.Player

class PAPIExpansion : PlaceholderExpansion() {
	val pl = VagueEnchants.pl

	override fun getVersion() = pl.description.version ?: "1.0.0"

	override fun getAuthor() = "hhhapz"

	override fun getIdentifier() = "vagueenchant"

	override fun persist() = true

	override fun canRegister() = true

	override fun onPlaceholderRequest(p: Player?, id: String): String {
		if (p == null) return "UNKNOWN_PLAYER"

		if (id == "token") return cachedTokens[p.uuid]?.toString() ?: 0.toString()
		val item = p.inventory.itemInMainHand
		val enchants = item.enchantments
		val args = id.split("_", limit = 2)

		if (args.component1() == "repair") {
			val fullCost = enchants.toList()
				.sumByBigDecimal { (k, v) -> k.fullCost(v) }
				.toDouble() * Config.repairValue
			return fullCost.toLong().toString()
		}

		if (args.size == 1) return "UNKNOWN_ARGUMENT"
		val ench = args.component1().ench()?: return "UNKNOWN_ENCHANTMENT"
		val level = enchants[ench]?: 0

		return ench.papiProperty(args.component2(), level)
	}
}

fun String.ench(): Enchantment? = Enchantment.getByName(toUpperCase()) ?: run {
	if (toUpperCase() == "EFFICIENCY") return Enchantment.DIG_SPEED
	if (toUpperCase() == "FORTUNE") return Enchantment.LOOT_BONUS_BLOCKS
	null
}