package pw.hamzantal.mdranks.api

import net.milkbowl.vault.economy.Economy
import net.milkbowl.vault.economy.EconomyResponse
import net.milkbowl.vault.permission.Permission
import org.bukkit.entity.Player
import pw.hamzantal.mdranks.MDRanks
import pw.hamzantal.mdranks.Ranks


object Vault {

	private val pl = MDRanks.pl

	val econ by lazy {
		if (pl.server.pluginManager.getPlugin("Vault") == null) {
			throw IllegalStateException("The vault dependency was not found")
		}
		pl.server.servicesManager.getRegistration(Economy::class.java).provider!!
	}

	val perms by lazy {
		if (pl.server.pluginManager.getPlugin("Vault") == null) {
			throw IllegalStateException("The vault dependency was not found")
		}
		pl.server.servicesManager.getRegistration(Permission::class.java).provider!!
	}


	fun withdraw(p: Player, amount: Number, onError: EconomyResponse.() -> Unit): Double {
		if (!econ.hasAccount(p)) econ.createPlayerAccount(p)
		val success = econ.withdrawPlayer(p, amount.toDouble())
		if (!success.transactionSuccess()) {
			success.onError()
			throw IllegalStateException("Fail on Withdraw: ${success.errorMessage}")
		}
		return econ.getBalance(p)
	}

	fun balance(p: Player) = econ.getBalance(p)

	fun updateRank(p: Player, type: RankType, level: Int, manual: Boolean = false) {
		if (level == 0 && type == RankType.REG) {
			updateRank(p, type, 1, manual)
			return
		}

		if (manual) {
			val current = Perms.rankFor(p, type)
			type.config(current).addPerms.forEach { perms.playerRemove(null, p, it) }
		}

		Ranks[p, type.rankName] = level

		p.effectivePermissions
			.filter { it.value && it.permission.startsWith("mdranks.${type.rankName}") }
			.forEach { perms.playerRemove(null, p, it.permission) }
		if (level == 0) return

		val config = type.config(level)
		config.addPerms.forEach { perms.playerAdd(null, p, it) }
		config.delPerms.forEach { perms.playerRemove(null, p, it) }
		perms.playerAdd(null, p, "mdranks.${type.rankName}.$level")
	}
}