package pw.hamzantal.mdranks

import hazae41.minecraft.kutils.bukkit.BukkitPlugin
import hazae41.minecraft.kutils.bukkit.command
import hazae41.minecraft.kutils.bukkit.listen
import hazae41.minecraft.kutils.bukkit.msg
import hazae41.minecraft.kutils.get
import org.bukkit.Bukkit
import org.bukkit.entity.Player
import org.bukkit.event.player.PlayerJoinEvent
import pw.hamzantal.mdranks.api.Perms
import pw.hamzantal.mdranks.api.RankType
import pw.hamzantal.mdranks.api.Vault
import pw.hamzantal.mdranks.commands.checkBalance
import pw.hamzantal.mdranks.commands.onPrestige
import pw.hamzantal.mdranks.commands.onRankUp
import pw.hamzantal.mdranks.commands.onRebirth

class MDRanks : BukkitPlugin() {
	companion object {
		lateinit var pl: MDRanks
	}

	val ranksFile = dataFolder["ranks.yml"]


	override fun onEnable() {
		pl = this
		saveDefaultConfig()

		listen<PlayerJoinEvent> {
			val p = it.player
			val lvl = Perms.reg(p)
			if (lvl == 0)
				Vault.updateRank(p, RankType.REG, 1)

			val regLevel = Perms.reg(p)
			val prLevel = Perms.prestige(p)
			val rbLevel = Perms.rebirth(p)
			Ranks[p, "regular"] = regLevel
			Ranks[p, "prestige"] = prLevel
			Ranks[p, "rebirth"] = rbLevel
		}

		command("mdranks") { sender, args ->
			if (!sender.hasPermission("mdranks.admin")) {
				sender.err("no_access")
				return@command
			}
			if  (args.size == 2) {
				val (player, toReset) = args
				val p = Bukkit.getPlayer(player)?: run {
					sender.err("player_not_found")
					return@command
				}
			}
			if (args.size < 3) {
				sender.err("mdranks_usage")
				return@command
			}
			val (player, type, num) = args
			val p = Bukkit.getPlayer(player) ?: run {
				sender.err("player_not_found")
				return@command
			}
			val rank = RankType.byArg(type) ?: run {
				sender.sendMessage("rank_not_found")
				return@command
			}
			val level = num.toIntOrNull() ?: 0

			Vault.updateRank(p, rank, level, true)
			sender.success(
				"update_player_rank_sender",
				"player" to p.name,
				"rank" to rank.rankName,
				"level" to "$level"
			)
			p.general(
				"update_player_rank_receiver",
				"rank" to rank.rankName,
				"level" to "$level"
			)
		}
		command("rankup") { args ->
			onRankUp(this, args)
		}
		command("prestige") { args ->
			onPrestige(this, args)
		}
		command("rebirth") { _ ->
			onRebirth(this)
		}
		command("bal") { args -> checkBalance(this, args) }
		command("rebirthtop") { _ ->
			msg("&a&m-------&f&m-------&a&m-------&f&m-------&a&m-------&f&m-------&a&m-------")
			Ranks.top.forEachIndexed { i, rank ->
				msg("&f&l#${i + 1}. &a${rank.name} &8» &7${rank.rebirth} Rebirth${if (rank.rebirth != 1) "s" else ""}")
			}
			msg("&a&m-------&f&m-------&a&m-------&f&m-------&a&m-------&f&m-------&a&m-------")
		}

		if (isPapi) PapiExpansion().register()
	}
}