import { world, ScriptEventCommandMessageAfterEvent, EntityLoadAfterEvent, system, EntityDamageCause, Entity } from "@minecraft/server";
import { Server } from "../../libs/Core/index.js";

class SetOnSoulFire {
    constructor() {
        this.#initEvents();
    }

    /**
     * 
     * @param {Entity} entity 
     */
    setOnSoulFire(entity, duration) {
        this.#setFire(entity, duration);
    }

    #initEvents() {
        Server.scriptEventManager.registerEvent('set_on_soul_fire', this.#setOnSoulFire.bind(this));
        world.afterEvents.entityLoad.subscribe(this.#onEntityLoad.bind(this));
    }

    /**
     * 
     * @param {EntityLoadAfterEvent} e 
     */
    #onEntityLoad(e) {
        if (e.entity.typeId === 'plank_waao:soul_flame_visual') e.entity.remove();
    }


    /**
     * 
     * @param {ScriptEventCommandMessageAfterEvent} e 
     */
    #setOnSoulFire(e, duration) {
        this.#setFire(e.sourceEntity, duration = 80);
    }

    /**
     * 
     * @param {Entity} e 
     */
    #setFire(e, duration) {
        duration = duration || 80;
        const createSoulFireEntity = () => e.dimension.spawnEntity(
            'plank_waao:soul_flame_visual',
            { ...e.location, y: e.location.y + 2 }
        )

        const clearRun = (handler) => {
            try {
                running = false;
                system.clearRun(handler);
                soulFireEntity.remove();
            } catch { }
        }

        let soulFireEntity = createSoulFireEntity();
        const startTick = system.currentTick - 20;
        let running = true;

        const handler = system.runInterval(() => {
            if (!running) return
            if (!e.isValid()) {
                clearRun(handler)
                return;
            }
            if (!soulFireEntity.isValid()) {
                soulFireEntity = createSoulFireEntity();
            }

            const tick = system.currentTick - startTick
            if (tick % 15 === 0) e.applyDamage(2, { cause: EntityDamageCause.fireTick });

            soulFireEntity.clearVelocity();
            soulFireEntity.teleport({ ...e.location, y: e.location.y + 7 });
        });

        system.runTimeout(() => {
            clearRun(handler)
        }, duration);
    }
}


export const setOnSoulFire = new SetOnSoulFire();