package pw.hamzantal.vagueenchants.commands

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

class AddEnch : Cmd {

	override val firstArg = "addench"
	override val usage = "/ve addench [player] [enchantment] [level]"
	override val minArgs = 4
	override val description = "&7Add an enchantment to the tool you are holding for target player"

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

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

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

		val level = lvl.toIntOrNull() ?: run {
			sender.err("The value $lvl was not parsed as a number. Using 1 instead.")
			1
		}
		if (level <= 0) {
			sender.err("level_below_zero")
			return
		}

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

		val success = if (ench is CustomEnchant) ench.customEnchant(item, level)
		else item.addUnsafeEnchantment(ench, level) == Unit
		if (ench is OmniTool) target.inventory.itemInMainHand = item.unbreakable(true)

		if (success) {
			sender.success("&aEnchantment successfully applied")
			target.success("addench_receiver")
		} else sender.err("general_error")
	}
}