package pw.hamzantal.vagueenchants.enchantments

import hazae41.minecraft.kutils.bukkit.listen
import hazae41.minecraft.kutils.bukkit.msg
import hazae41.minecraft.kutils.bukkit.schedule
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.player.PlayerItemHeldEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType.FAST_DIGGING
import pw.hamzantal.vagueenchants.Config
import pw.hamzantal.vagueenchants.ToolUtils
import pw.hamzantal.vagueenchants.VagueEnchants
import pw.hamzantal.vagueenchants.commands.c
import pw.hamzantal.vagueenchants.x

class Haste(id: Int) : CustomEnchant(id, Config.haste, "HASTE"), Listener {

	init {
		VagueEnchants.enchants += this
		val pl = VagueEnchants.pl
		pl.registerEnchantment(this)
		pl.listen(callback = this::onItemHeld)
		pl.schedule(delay = 2, period = 2) {
			Bukkit.getOnlinePlayers().forEach { p ->
				val enchs = p.inventory.itemInMainHand?.enchantments ?: mapOf()
				val effect = PotionEffect(FAST_DIGGING, 50, (enchs[this@Haste] ?: 1) - 1)
				if (this@Haste in enchs) {
					p.addPotionEffect(effect, true)
				}
			}
		}
	}

	private fun onItemHeld(e: PlayerItemHeldEvent) {
		val p = e.player
		val now = p.inventory.getItem(e.newSlot)
		val before = p.inventory.getItem(e.previousSlot)
		if (now != null && this in now.enchantments)
			p.addPotionEffect(PotionEffect(FAST_DIGGING, 50, now.enchantments[this]!! - 1))
		else if (before != null && this in before.enchantments) p.removePotionEffect(FAST_DIGGING)
	}

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

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

}