package pw.hamzantal.vagueenchants.commands

import com.okkero.skedule.SynchronizationContext
import com.okkero.skedule.schedule
import org.bukkit.Bukkit
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import pw.hamzantal.vagueenchants.VagueEnchants
import pw.hamzantal.vagueenchants.getTokens
import pw.hamzantal.vagueenchants.setTokens
import pw.hamzantal.vagueenchants.uuid

fun tokenCommand(s: CommandSender, arg: Array<String>) {
	if (arg.isEmpty()) {
		if (s !is Player) {
			s.err("require_player")
			return
		}
		Bukkit.getScheduler().schedule(VagueEnchants.pl, initialContext = SynchronizationContext.ASYNC) {
			val tokens = getTokens(s.uuid)
			s.general("tokens", "token" to "$tokens")
		}
		return
	}

	if (arg.component1() == "give") {
		if (s !is Player) {
			s.err("require_player")
			return
		}
		giveCommand(s, arg)
		return
	}

	val (targetName) = arg
	val target = Bukkit.getOfflinePlayer(targetName)

	Bukkit.getScheduler().schedule(VagueEnchants.pl, initialContext = SynchronizationContext.ASYNC) {
		val tokens = getTokens(target.uuid)
		s.general("tokens_other", "player" to targetName, "token" to "$tokens")
	}
}

fun giveCommand(s: Player, arg: Array<String>) {
	if (arg.size != 3) {
		s.general("/token give [player] [amount]")
		return
	}

	val (_, targetName, amt) = arg
	val target = Bukkit.getPlayer(targetName) ?: run {
		s.err("target_not_found", "player" to targetName)
		return
	}
	val amount = (amt.toIntOrNull() ?: 0)
	if (amount < 0) {
		s.err("amount_below_zero")
		return
	}
	val tokens = getTokens(s.uuid)
	val targetTokens = getTokens(target.uuid)
	if (tokens < amount) {
		s.err("not_enough_tokens")
		return
	}
	if (tokens < 0L) {
		s.err("amount_below_zero")
		return
	}

	setTokens(s.uuid, tokens - amount)
	setTokens(target.uuid, targetTokens + amount)
	s.general("tokens_give_sender", "token" to "${tokens - amount}", "player" to targetName)
	if (target.isOnline)
		target.general("tokens_give_receiver", "token" to "${tokens + amount}", "player" to s.name)
	return
}