package pw.hamzantal.mdranks.commands

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

fun onRankUp(p: CommandSender, args: Array<String>) {
	if (p !is Player) {
		p.err("rankup_not_player")
		return
	}
	if (args.isNotEmpty() && args.first() == "max") return onRankupMax(p)

	val current = RegularConfig(Perms.reg(p))
	if (current.isLast) {
		p.err("rankup_max")
		return
	}

	val next = RegularConfig(current.level + 1)
	if (!rankUpgradePrerequisites(p, next)) {
		p.err("rankup_not_enough_money", "cost" to Config.formatC(next.cost(p)))
	}
}

fun onRankupMax(p: Player) {
	val currentLevel = Perms.reg(p)
	val current = RegularConfig(currentLevel)
	if (current.isLast) {
		p.err("rankup_max")
		return
	}

	var nextLevel = currentLevel + 1
	while (nextLevel <= RegularConfig.max()) {
		val next = RegularConfig(nextLevel)
		if (!rankUpgradePrerequisites(p, next)) {
			if (nextLevel == currentLevel + 1)
				p.err("rankup_not_enough_money", "cost" to Config.formatC(next.cost(p)))
			return
		}
		nextLevel++
	}
}



