package pw.hamzantal.mdranks.commands

import org.bukkit.Bukkit
import org.bukkit.entity.Player
import pw.hamzantal.mdranks.Config
import pw.hamzantal.mdranks.RankData
import pw.hamzantal.mdranks.api.RankType
import pw.hamzantal.mdranks.api.Vault
import pw.hamzantal.mdranks.err
import pw.hamzantal.mdranks.placeholders

fun rankUpgradePrerequisites(p: Player, next: RankData, type: RankType = RankType.REG): Boolean {
	val balance = Vault.balance(p)
	val cost = next.cost(p)
	if (balance < cost) {
		return false
	}
	Vault.withdraw(p, cost) {
		p.err("unknown_error_withdraw", "cost" to Config.formatC(cost))
	}
	performUpgradeRank(p, next, type)
	return true
}

fun performUpgradeRank(p: Player, data: RankData, type: RankType) {
	Vault.updateRank(p, type, data.level)
	if (type == RankType.REBIRTH) {
		Vault.updateRank(p, RankType.REG, 1, true)
		Vault.updateRank(p, RankType.PRESTIGE, 0, true)
	}

	data.commandsOnUpgrade.forEach {
		it.executeCommandWithPrefix(p, data)
	}
	data.broadcast.forEach {
		val msg = it.placeholders(p, data)
		Bukkit.broadcastMessage(msg)
	}
	data.msg.forEach {
		val msg = it.placeholders(p, data)
		p.sendMessage(msg)
	}
	data.randomCommandList.forEach {
		it.executeCommandWithPrefix(p, data)
	}
}

fun String.executeCommandWithPrefix(p: Player, data: RankData) {
	val cmd = placeholders(p, data, true)
	when {
		startsWith("[console]") -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd)
		startsWith("[player]") -> p.performCommand(cmd)
		startsWith("[op]") -> {
			val prev = p.isOp
			p.isOp = true
			p.performCommand(cmd)
			p.isOp = prev
		}
		else -> throw IllegalStateException("The [commandsOnUpgrade ($this), level (${data.level})] command does not start with a prefix")
	}
}