
import { world, system } from "@minecraft/server";
import { MISSILE_TYPE, dimensions, activeTickingAreas, tickingAreaNames, missileStates, missileVelocities } from "./HomingMissile.js";

export function cleanupMissile(missileId) {
    
    const areaName = tickingAreaNames.get(missileId);
    
    if (areaName) {
        for (const dimId of dimensions) {
            const dimension = world.getDimension(dimId);
            if (dimension) {
                system.runTimeout(() => {
                    try {
                        dimension.runCommand(`tickingarea remove ${areaName}`);
                    } catch (e) {}
                }, 1);
            }
        }
    }
    
    system.runTimeout(() => {
        activeTickingAreas.delete(areaName);
        missileStates.delete(missileId);
        missileVelocities.delete(missileId);
        tickingAreaNames.delete(missileId);
    }, 2);
}
world.afterEvents.entityRemove.subscribe((ev) => {
    const removed = ev.removedEntity;
    if (removed?.typeId === MISSILE_TYPE) {
        
        const areaName = tickingAreaNames.get(removed.id);
        if (areaName) {
            for (const dimId of dimensions) {
                const dimension = world.getDimension(dimId);
                if (dimension) {
                    system.runTimeout(() => {
                        try {
                            dimension.runCommand(`tickingarea remove ${areaName}`);
                        } catch (e) {}
                    }, 1);
                }
            }
        }
        cleanupMissile(removed.id);
    }
});

world.afterEvents.entityDie.subscribe((ev) => {
    const dead = ev.deadEntity;
    if (dead?.typeId === MISSILE_TYPE) {
        
        const areaName = tickingAreaNames.get(dead.id);
        if (areaName) {
            for (const dimId of dimensions) {
                const dimension = world.getDimension(dimId);
                if (dimension) {
                    system.runTimeout(() => {
                        try {
                            dimension.runCommand(`tickingarea remove ${areaName}`);
                        } catch (e) {}
                    }, 1);
                }
            }
        }
        cleanupMissile(dead.id);
    }
});


