package pw.hamzantal.vagueenchants

import org.bukkit.enchantments.Enchantment
import pw.hamzantal.vagueenchants.enchantments.CustomEnchant
import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode

fun Enchantment.papiProperty(prop: String, level: Int): String {
	val config = conf()?: return ""
	return when (prop) {
		"level" -> level.toString()
		"next_level" -> if (level + 1 > config.max) maxLevel.toString() else "${level + 1}"
		"cost" -> if (level + 1 > config.max) "0" else config.cost.x(level + 1).round.toInt().toString()
		"max" -> config.max.toString()
		"description" -> config.description
		"refund_cost" -> refund(level).toLong().toString()
		else -> ""
	}
}

fun Enchantment.conf(): EnchantmentInfo? {
	return when {
		this is CustomEnchant -> config
		this == Enchantment.DIG_SPEED -> Config.fortune
		this == Enchantment.LOOT_BONUS_BLOCKS -> Config.fortune
		else -> null
	}
}

fun Enchantment.refund(level: Int): BigDecimal {
	println(BigDecimal(Config.refundValue).round)
	return fullCost(level).multiply(BigDecimal(Config.refundValue).round)
}

fun Enchantment.fullCost(level: Int): BigDecimal {
	return if (this is CustomEnchant) {
		(1..level).toList()
			.sumByBigDecimal { config.cost.x(it) }
	} else BigDecimal.ZERO
}

inline fun <T> Iterable<T>.sumByBigDecimal(selector: (T) -> BigDecimal): BigDecimal {
	var sum: BigDecimal = BigDecimal.ZERO
	for (element in this) {
		sum += selector(element)
	}
	return sum.round
}

val BigDecimal.round: BigDecimal get() = setScale(2, RoundingMode.HALF_UP)

val BigDecimal.int: Int get() = round.toInt()