package pw.hamzantal.bloodmoon

import hazae41.minecraft.kutils.bukkit.msg
import hazae41.minecraft.kutils.bukkit.schedule
import me.libraryaddict.disguise.disguisetypes.DisguiseType
import me.libraryaddict.disguise.disguisetypes.MobDisguise
import org.bukkit.Bukkit
import org.bukkit.entity.*

object BMData {
    var running = false

    var bm = BloodMoon.pl
    val transformed = hashMapOf<MobDisguise, LivingEntity>()
    val creepers = mutableListOf<Creeper>()

    fun ticksLeft(): Int {
        return (23460 - Config.world.time).toInt()
    }

    fun begin() {
        stop()
        println(Config.enabledMobs)
        Config.world.entities.forEach { en ->
            if (!Config.enabledMobs.contains(en.type.toString().toUpperCase())) {
                return@forEach
            }
            en.remove()
            val blood = en.world.spawnEntity(en.location, EntityType.ZOMBIE).apply {
                (this as Zombie).isBaby = true
                customName = "§cBlood ${en.name}"
                isCustomNameVisible = true
            }
            val disguise = MobDisguise(DisguiseType.valueOf(en.type.name))
            disguise.entity = blood
            disguise.startDisguise()
            transformed[disguise] = en as LivingEntity
        }
        if (Config.chargedCreepers) Config.world.entities.filter { it is Creeper }.forEach {
            (it as Creeper).isPowered = true
            creepers += it
        }

        Bukkit.getOnlinePlayers().forEach { it.msg(Config.startMessage.c) }
        running = true
        bm.schedule(delay = ticksLeft() / 20L) {
            stop()
            Bukkit.getOnlinePlayers().forEach { it.msg(Config.endMessage.c) }
        }
    }

    fun stop() {
        println("stopping...")
        running = false
        transformed.forEach { (d, e) ->
            d.entity.remove()
            d.stopDisguise()
            d.entity.world.spawnEntity(d.entity.location, e.type).apply {
                (this as LivingEntity).health = e.health
                if (this is Sheep) color = (e as Sheep).color
            }
        }
        transformed.clear()
        creepers.forEach { it.isPowered = false }
        creepers.clear()
    }
}