import { BrickDisplay, BrickDisplayImage } from "@common/display/brick";
import { Position } from "@common/rpg/components/position";
import { BrickSprite } from "@common/rpg/components/render/brick";
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 BrickDisplaySystem extends System {
    public readonly display: BrickDisplay;

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

    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 { xor = false, miniDisplay = false } = e.get(BrickSprite)?.state ?? {};

            const { x, y } = pos.state;

            const data = Resources.get(BrickDisplayImage, sprite.image);
            if (!data) {
                throw new Error('No image data found for sprite');
            }
            this.display.drawImage(data, x, y, miniDisplay, xor);
        }
    }
}