package pw.hamzantal.vagueenchants.enchantments

import hazae41.minecraft.kutils.bukkit.listen
import hazae41.minecraft.kutils.bukkit.msg
import org.bukkit.Bukkit
import org.bukkit.enchantments.Enchantment
import org.bukkit.enchantments.EnchantmentTarget
import org.bukkit.entity.Player
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.inventory.ItemStack
import pw.hamzantal.vagueenchants.*
import pw.hamzantal.vagueenchants.commands.c
import java.math.BigDecimal
import java.util.*

class KeyMine(id: Int) : CustomEnchant(id, Config.keyMine, "KEYMINE"), Listener {

	init {
		VagueEnchants.enchants += this
		val pl = VagueEnchants.pl
		pl.listen(callback = this::onBreak)
		pl.registerEnchantment(this)
	}

	private val r = Random()
	private val cachedProb = hashMapOf<Player, Pair<BigDecimal, Long>>()

	private fun onBreak(e: BlockBreakEvent) {
		val p = e.player
		if (this !in p.inventory.itemInMainHand?.enchantments ?: mapOf()) return
		val level = p.inventory.itemInMainHand.enchantments[this]!!
		if (p !in cachedProb || cachedProb[p]!!.second > System.currentTimeMillis())
			cachedProb[p] = config.chance.x(level, scale = false) to System.currentTimeMillis() + 30 * 1000

		val chance = cachedProb[p]!!.first
		val rdm = r.nextDouble()

		if (!e.block.location.canMine(p)) return
		if (chance.toDouble() <= rdm) return

		val command = config.keys.shuffled().first().papi(p)
		Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
	}

	override fun inspect(p: Player, level: Int) {
		val cost = config.cost.x(level + 1)
		val chance = config.chance.x(level, scale = false)
		p.msg("&7Description: ${config.description}")
		p.msg("&7Current level: $level")
		p.msg("&7Maximum level: ${config.max}")
		if (level < maxLevel) p.msg("&7Next level cost: $cost")
		else p.msg("&7Level maxed")

		p.msg("&7Chance to receive a key: $chance")
	}

	override fun loreString(level: Int): String {
		return "&7Key Mine ${loreLevel(level)}".c
	}
}