import { Effect } from "../components/effect";
import { Component, System, type Entity, type World } from "../core/world";
import { evaluateCondition } from "../utils/conditions";

export class EffectSystem extends System {
    override update(world: World, dt: number) {
        const expired: [Entity, Component<any>][] = [];

        for (const [entity, , effect] of world.query(Effect)) {
            if (effect.state.remaining != null) {
                if (effect.state.remaining > 0) {
                    effect.state.remaining -= dt;
                    if (effect.state.remaining <= 0) {
                        effect.clear();
                    }

                    if (effect.state.gradual && effect.state.duration) {
                        const delta = effect.state.delta * dt / effect.state.duration;
                        effect.applyDelta(delta);
                    }
                }
            } else if (effect.state.condition != null) {
                if (!evaluateCondition(effect.state.condition, effect.entity)) {
                    effect.clear();
                }
            }
            if (effect.state.remaining !== null && effect.state.remaining <= 0) {
                expired.push([entity, effect]);
            }
        }

        for (const [entity, key] of expired) {
            entity.remove(key);
        }
    }
}
