package pw.hamzantal.bloodmoon

import hazae41.minecraft.kutils.bukkit.command
import hazae41.minecraft.kutils.bukkit.listen
import hazae41.minecraft.kutils.bukkit.msg
import hazae41.minecraft.kutils.bukkit.schedule
import org.bukkit.Bukkit
import org.bukkit.event.Listener
import org.bukkit.event.entity.*
import org.bukkit.plugin.java.JavaPlugin
import pw.hamzantal.bloodmoon.listeners.*
import kotlin.random.Random

class BloodMoon : JavaPlugin(), Listener {
    companion object {
        lateinit var pl: BloodMoon
    }

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

        initListeners()

        schedule(async = false, period = 1, delay = 1) {
            if (Bukkit.getWorlds().first().fullTime - 13000 in 0..20) {
                val chance = Random.nextDouble()
                if (!BMData.running && chance < Config.chance) BMData.begin()
                else Bukkit.getOnlinePlayers().filter { it.isOp }.forEach {
                    it.msg("&c[!] &7Blood Moon chance did not meet threshold: ${String.format("%.02f", chance)} (must be between 0 and ${Config.chance}) ")
                }
            }
        }

command("bloodmoon") { sender, _ ->
    if (BMData.running) sender.msg("&c&lThe Blood Moon is Active!\n&7${BMData.ticksLeft() / 20} seconds left.")
    else sender.msg("&a&lThe Blood Moon is not currently active.")
}
    }

    override fun onDisable() {
        BMData.stop()
    }

    private fun initListeners() {
        listen<EntityDamageByEntityEvent> { zombieHit(it) }
        listen<EntityDamageEvent> { onFallDmg(it) }
        listen<ProjectileLaunchEvent> { onSkellyShoot(it) }
        listen<CreatureSpawnEvent> { onCreatureSpawn(it) }
        listen<EntityDeathEvent> { onDeath(it) }
    }
}