package pw.hamzantal.vagueenchants.commands

import hazae41.minecraft.kutils.bukkit.msg
import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.command.CommandSender
import pw.hamzantal.vagueenchants.*
import java.math.BigDecimal
import kotlin.math.max

class Repair : Cmd {

	override val firstArg = "repair"
	override val usage = "/ve repair [player]"
	override val minArgs = 2
	override val description = "&7Repair a player's tool."

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

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

		val target = Bukkit.getPlayer(targetName) ?: run {
			sender.err("target_not_found", "player" to targetName)
			return
		}
		val item = target.inventory.itemInMainHand
		if (item == null || item.type == Material.AIR) {
			target.err("no_item_held")
			return
		}

		val current = item.enchantments
		val rawCost = current.toList()
			.sumByBigDecimal { (k, v) -> k.fullCost(v) }
			.multiply(BigDecimal(Config.repairValue)).round
			.toLong()
		val cost = max(Config.minRepair, rawCost)

		val tokens = getTokens(target.uuid)
		if (tokens < cost) {
			target.err("repair_not_enough", "token" to "$cost")
			return
		}
		setTokens(target.uuid, tokens - cost)

		target.success("repair_receiver")
		item.durability = 0
	}
}