package pw.hamzantal.vagueenchants.commands

import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.command.CommandSender
import pw.hamzantal.vagueenchants.*
import pw.hamzantal.vagueenchants.enchantments.CustomEnchant
import pw.hamzantal.vagueenchants.enchantments.OmniTool

class Refund : Cmd {

	override val firstArg = "refund"
	override val usage = "/ve refund [player] [enchantment]"
	override val minArgs = 3
	override val description = "&7Refund an enchantment for the tool a player is holding."

	override val requirePermission = true
	override val permission = "ve.admin"
	override val requirePlayer = false

	override fun execute(sender: CommandSender, args: Array<String>) {
		val (_, targetName, enchName) = args

		val target = Bukkit.getPlayer(targetName) ?: run {
			sender.err("target_not_found", "player" to targetName)
			return
		}
		val ench = enchName.ench(sender) ?: return

		val item = target.inventory.itemInMainHand
		if (item == null || item.type == Material.AIR) {
			target.err("no_item_held")
			return
		}

		val current = item.enchantments[ench] ?: run {
			target.err("no_enchants")
			return
		}

		val refund = ench.refund(current).toLong()

		val tokens = getTokens(target.uuid)

		val success = if (ench is CustomEnchant) !ench.customEnchant(item, 0)
		else item.removeEnchantment(ench) == 0

		if (ench is OmniTool) target.inventory.itemInMainHand = item.unbreakable(true)

		if (success) {
			setTokens(target.uuid, tokens + refund)
			target.success("refund_receiver")
		} else sender.err("general_error")
	}
}