import { TextRegion, TextDisplay } from "@common/display/text";
import { Position } from "@common/rpg/components/position";
import { Hidden, Sprite } from "@common/rpg/components/sprite";
import { System, World } from "@common/rpg/core/world";
import { Resources } from "@common/rpg/utils/resources";

export class TextDisplaySystem extends System {
    public readonly display: TextDisplay;

    constructor(display?: TextDisplay) {
        super();
        this.display = display ?? new TextDisplay();
    }

    override update(world: World) {
        const sprites = Array.from(world.query(Sprite, Position)).sort((a, b) => a[2].state.z - b[2].state.z);
        for (const [e, sprite, pos] of sprites) {
            if (e.has(Hidden)) continue;
            const image = sprite.image;
            const { x, y } = pos.state;

            const data =
                Resources.get(TextRegion, image)
                ?? Resources.get(String, image)
                ?? image;

            const region = data instanceof TextRegion ? data : new TextRegion(data);
            this.display.setRegion(x, y, region);
        }
    }
}