import {} from "../Entity.js";
import {} from "../System.js";
import {} from "../World.js";
import { ActiveComponent } from "../components/ActiveComponent.js";
import { HierarchyComponent } from "../components/HierarchyComponent.js";
export class ActiveSystem {
    name = "ActiveSystem";
    phase = "update";
    priority = -90;
    onActiveChanged;
    update(world, _context) {
        const memo = new Map();
        const entities = world.query({ include: [ActiveComponent] }).toArray().sort((left, right) => {
            return (world.get(left, HierarchyComponent)?.depth ?? 0) - (world.get(right, HierarchyComponent)?.depth ?? 0);
        });
        for (const entity of entities) {
            const component = world.get(entity, ActiveComponent);
            if (!component)
                continue;
            const previous = component.activeInHierarchy;
            component.activeInHierarchy = computeActiveInHierarchy(world, entity, memo);
            if (previous !== component.activeInHierarchy)
                this.onActiveChanged?.(entity, component.activeInHierarchy);
        }
    }
    setActive(world, entity, active) {
        let component = world.get(entity, ActiveComponent);
        if (!component) {
            component = new ActiveComponent(active);
            world.add(entity, ActiveComponent, component);
        }
        else {
            component.setActive(active);
        }
        this.update(world, { deltaTime: 0, elapsedTime: 0, frame: 0 });
    }
    isActive(world, entity) {
        return world.get(entity, ActiveComponent)?.activeSelf ?? true;
    }
    isActiveInHierarchy(world, entity) {
        return world.get(entity, ActiveComponent)?.activeInHierarchy ?? true;
    }
    getActiveEntities(world) {
        return world.query({ include: [ActiveComponent] }).toArray().filter((entity) => this.isActiveInHierarchy(world, entity));
    }
    getInactiveEntities(world) {
        return world.query({ include: [ActiveComponent] }).toArray().filter((entity) => !this.isActiveInHierarchy(world, entity));
    }
}
function computeActiveInHierarchy(world, entity, memo) {
    const key = `${entity.id}:${entity.generation}`;
    const cached = memo.get(key);
    if (cached !== undefined)
        return cached;
    const activeSelf = world.get(entity, ActiveComponent)?.activeSelf ?? true;
    const parent = world.get(entity, HierarchyComponent)?.parent ?? null;
    const active = activeSelf && (parent ? computeActiveInHierarchy(world, parent, memo) : true);
    memo.set(key, active);
    return active;
}
//# sourceMappingURL=ActiveSystem.js.map