package pw.hamzantal.vagueenchants

import com.sk89q.worldguard.bukkit.WorldGuardPlugin
import com.sk89q.worldguard.protection.flags.StateFlag
import com.sk89q.worldguard.protection.regions.ProtectedRegion
import com.udojava.evalex.Expression
import me.clip.placeholderapi.PlaceholderAPI
import net.minecraft.server.v1_10_R1.NBTTagCompound
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.OfflinePlayer
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack
import org.bukkit.enchantments.Enchantment
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import pw.hamzantal.vagueenchants.enchantments.CustomEnchant
import java.math.BigDecimal
import java.math.RoundingMode

fun Expression.x(value: Any, scale: Boolean = true) = with("x", value.toString()).eval().run {
	if (scale) setScale(2, RoundingMode.HALF_DOWN)
	else this
} ?: BigDecimal.ZERO

val OfflinePlayer.uuid: String get() = uniqueId.toString()

val isPapi by lazy { Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null }

fun String.papi(p: Player) =
	(if (isPapi) PlaceholderAPI.setPlaceholders(p, this)!! else this.replace("%player%", p.name))
		.replace("%player%", p.name)

fun Location.validRegion(p	: Player): ProtectedRegion? {
	if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) return null

	val manager = WorldGuardPlugin.inst().regionContainer.get(world) ?: return null
	val regions = manager.getApplicableRegions(this) ?: return null
	return regions.regions
		.filter { canMine(p) }
		.firstOrNull { r ->
			r.flags.entries.any {
				it.key.name == "block-break" && it.value == StateFlag.State.ALLOW
			}
		} ?: return null
}

fun Location.canMine(p: Player): Boolean {
	if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) {
		println("WorldGuard not found!")
		return true
	}
	val wP = WorldGuardPlugin.inst().wrapPlayer(p)
	val qry = WorldGuardPlugin.inst().regionContainer.createQuery()
	return qry.testState(this, wP, StateFlag("block-break", true))
}

fun ItemStack.unbreakable(to: Boolean): ItemStack {
	val stack = CraftItemStack.asNMSCopy(this)
	val tag = stack.tag ?: NBTTagCompound()
	tag.setBoolean("Unbreakable", to)
	stack.tag = tag
	return CraftItemStack.asBukkitCopy(stack)
}