package pw.hamzantal.mdranks.commands

import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import pw.hamzantal.mdranks.Config
import pw.hamzantal.mdranks.PrestigeConfig
import pw.hamzantal.mdranks.RegularConfig
import pw.hamzantal.mdranks.api.Perms
import pw.hamzantal.mdranks.api.RankType
import pw.hamzantal.mdranks.err

fun onPrestige(p: CommandSender, args: Array<String>) {
	if (p !is Player) {
		p.err("prestige_not_player")
		return
	}
	val regMax = RegularConfig.max()
	if (regMax != Perms.reg(p)) {
		p.err(
			"prestige_not_max_rankup",
			"rankup_display" to RegularConfig(regMax).display,
			"rankup" to "$regMax"
		)
		return
	}

	if (args.isNotEmpty() && args.first() == "max") return onPrestigeMax(p)

	val currentLevel = Perms.prestige(p)
	if (currentLevel != 0) {
		val current = PrestigeConfig(currentLevel)

		if (current.isLast) {
			p.err("prestige_max")
			return
		}
	}

	val next = PrestigeConfig(currentLevel + 1)
	if (!rankUpgradePrerequisites(p, next, RankType.PRESTIGE)) {
		p.err("prestige_not_enough_money", "cost" to Config.formatC(next.cost(p)))
	}
}

fun onPrestigeMax(p: Player) {
	val currentLevel = Perms.prestige(p)
	if (currentLevel != 0) {
		val current = PrestigeConfig(currentLevel)

		if (current.isLast) {
			p.err("prestige_max")
			return
		}
	}
	var nextLevel = currentLevel + 1
	while (nextLevel <= PrestigeConfig.max()) {
		val next = PrestigeConfig(nextLevel)
		if (!rankUpgradePrerequisites(p, next, RankType.PRESTIGE)) {
			if (nextLevel == currentLevel + 1)
				p.err("prestige_not_enough_money", "cost" to Config.formatC(next.cost(p)))
			return
		}
		nextLevel++
	}

}
