import { system, world } from "@minecraft/server";
import { worldProxy } from "../worldProxy";
// better than querying world getentities every darn tick
export class EntityTracker {
    constructor() {
        this.entityTrack = new Map();
        world.afterEvents.worldInitialize.subscribe(() => {
            //iterate over all entities here
            for (const d of worldProxy.getKnownDimensions()) {
                for (const entity of d.getEntities()) {
                    if (this.shouldTrack(entity)) {
                        //console.log("Tracking block entity: " + entity.typeId);
                        this.entityTrack.set(entity.id, entity);
                    }
                }
            }
        });
        //we have a problem on reload...
        world.afterEvents.entitySpawn.subscribe((event) => {
            if (this.shouldTrack(event.entity)) {
                //console.log("Tracking Spawned block entity: " + event.entity.typeId);
                this.entityTrack.set(event.entity.id, event.entity);
            }
        });
        world.afterEvents.entityLoad.subscribe((event) => {
            if (this.shouldTrack(event.entity)) {
                //console.log("Tracking Loaded block entity: " + event.entity.typeId);
                this.entityTrack.set(event.entity.id, event.entity);
            }
        });
        world.afterEvents.entityRemove.subscribe((event) => {
            if (this.entityTrack.delete(event.removedEntityId)) {
                //console.log("Untracking unloaded block entity: " + event.typeId);
            }
        });
        system.runInterval(() => {
            for (const entity of this.entityTrack.values()) {
                if (!entity || !entity.isValid()) {
                    this.entityTrack.delete(entity.id);
                    continue;
                }
                if (entity.location.y < entity.dimension.heightRange.min) {
                    this.entityTrack.delete(entity.id);
                    entity.remove();
                    continue;
                }
                this.onTick(entity);
            }
        });
    }
    unTrack(entityId) {
        this.entityTrack.delete(entityId);
    }
}
