import { world, system } from "@minecraft/server";

const targetLaserTickingAreas = new Map();
let nextLaserTickingAreaId = 1;

function createTargetLaserTickingArea(laser, dimension) {
    const areaName = `tl${nextLaserTickingAreaId++}`;
    if (nextLaserTickingAreaId > 999) nextLaserTickingAreaId = 1;
    
    const x = Math.floor(laser.location.x);
    const y = Math.floor(laser.location.y);
    const z = Math.floor(laser.location.z);

    

    try {
        const removeCmd = `tickingarea remove ${areaName}`;
        try {
            dimension.runCommand(removeCmd);
            
        } catch (err) {}

        const addCmd = `tickingarea add circle ${x} ${y} ${z} 2 ${areaName}`;
        dimension.runCommand(addCmd);
        

        targetLaserTickingAreas.set(laser.id, {
            name: areaName,
            dimension: dimension,
            timeoutId: system.runTimeout(() => {
                
                removeTargetLaserTickingArea(laser.id, dimension);
            }, 600)
        });

        

    } catch (error) {
        
    }
}

function removeTargetLaserTickingArea(laserId, dimension) {
    const tickingArea = targetLaserTickingAreas.get(laserId);
    if (tickingArea) {
        
        
        try {
            dimension.runCommand(`tickingarea remove ${tickingArea.name}`);
            
        } catch (error) {
            
        }
        
        system.clearRun(tickingArea.timeoutId);
        targetLaserTickingAreas.delete(laserId);
        
    }
}

world.afterEvents.entityRemove.subscribe((ev) => {
    const removed = ev.removedEntity;
    if (!removed) return;

    if (removed.typeId === "ttav:target_laser") {
        
        removeTargetLaserTickingArea(removed.id, removed.dimension);
    }
});

world.afterEvents.entityDie.subscribe((ev) => {
    const dead = ev.deadEntity;
    if (!dead) return;
    
    if (dead.typeId === "ttav:target_laser") {
        
        removeTargetLaserTickingArea(dead.id, dead.dimension);
    }
});

export { createTargetLaserTickingArea, removeTargetLaserTickingArea };
