package pw.hamzantal.vagueenchants.enchantments

import hazae41.minecraft.kutils.bukkit.listen
import hazae41.minecraft.kutils.bukkit.msg
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
import pw.hamzantal.vagueenchants.Config
import pw.hamzantal.vagueenchants.VagueEnchants
import pw.hamzantal.vagueenchants.commands.c
import pw.hamzantal.vagueenchants.papi
import pw.hamzantal.vagueenchants.x

class AutoSell(id: Int) : CustomEnchant(id, Config.autoSell, "AUTOSELL"), Listener {

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

	private val cooldowns = hashMapOf<Player, Long>()

	private fun onBreak(e: BlockBreakEvent) {
		val p = e.player
		if (this !in p.inventory.itemInMainHand?.enchantments ?: mapOf()) return
		if (p in cooldowns && cooldowns[p]!! > System.currentTimeMillis()) return
		val level = p.inventory.itemInMainHand.enchantments[this]!!
		cooldowns[p] = System.currentTimeMillis() +
				1000 * config.cooldown.x(level).toLong()

		if (e.player.inventory.firstEmpty() == -1)
			Bukkit.dispatchCommand(e.player, config.command.papi(p))
	}


	override fun inspect(p: Player, level: Int) {
		val cost = config.cost.x(level + 1)
		val cd = config.cooldown.x(level)
		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("&7Cooldown between Auto Sell: $cd")
		if (p in cooldowns && cooldowns[p]!! > System.currentTimeMillis())
			p.msg("&7Cooldown remaining: ${(cooldowns[p]!! - System.currentTimeMillis()) / 1000} seconds")
	}

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