package pw.hamzantal.vagueenchants

import hazae41.minecraft.kutils.bukkit.command
import hazae41.minecraft.kutils.bukkit.listen
import hazae41.minecraft.kutils.bukkit.schedule
import org.bukkit.Bukkit
import org.bukkit.enchantments.Enchantment
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.plugin.java.JavaPlugin
import pw.hamzantal.vagueenchants.commands.VECompleter
import pw.hamzantal.vagueenchants.commands.tokenCommand
import pw.hamzantal.vagueenchants.enchantments.*
import java.lang.reflect.Field
import java.util.*

class VagueEnchants : JavaPlugin() {

	companion object {
		lateinit var pl: VagueEnchants
		val enchants = mutableListOf<Enchantment>()
	}

	override fun onEnable() {
		pl = this
		saveDefaultConfig()
		command("ve") { sender, args ->
			baseCommand(sender, args)
		}
		getCommand("ve").tabCompleter = VECompleter()
		command("token") { sender, args ->
			tokenCommand(sender, args)
		}

		tokens()
		enchantments()
		if (isPapi) PAPIExpansion().register()
	}

	private fun enchantments() {
		OmniTool(400)
		Speed(401)
		Haste(402)
		Explosive(403)
		AutoSell(404)
		KeyMine(405)
		TokenMiner(406)
		Slicing(407)
	}

	private fun tokens() {
		listen(callback = ::onJoin)
		listen(callback = ::onLeave)
		Bukkit.getOnlinePlayers().forEach { p -> cachedTokens[p.uuid] = getTokens(p.uuid) }
		schedule(async = true, delay = 60, period = 60) {
			cachedTokens.forEach { (k, v) -> setTokens(k, v, true) }
		}
	}

	override fun onDisable() {
		cachedTokens.forEach { (k, v) -> setTokens(k, v, true) }

		val byIdField = Enchantment::class.java.getDeclaredField("byId")
		val byNameField = Enchantment::class.java.getDeclaredField("byName")
		byIdField.isAccessible = true
		byNameField.isAccessible = true

		val byId = byIdField[null] as HashMap<*, *>
		val byName = byNameField[null] as HashMap<*, *>
		enchants.forEach { e ->
			@Suppress("DEPRECATION")
			byId.remove(e.id)
			byName.remove(e.name)

		}
	}

	fun registerEnchantment(enchantment: Enchantment) {
		val f: Field = Enchantment::class.java.getDeclaredField("acceptingNew")
		f.isAccessible = true
		f.set(null, true)
		Enchantment.registerEnchantment(enchantment)
	}
}