import { Component, type Entity, type World } from "@common/rpg/core/world";
import { Position } from "@common/rpg/components/position";
import { Sprite } from "@common/rpg/components/sprite";
import { ITEM_SPRITE } from "./images";
import { Item, Items } from "@common/rpg/components/item";
import { component } from "@common/rpg/utils/decorators";

@component
class PickupCount extends Component<{ count: number }> {
    constructor(count = 1) {
        super({ count });
    }
}

export function findItem(world: World, id: number): Entity | undefined {
    for (const [item, , component] of world.query(Item)) {
        if (component.state.name === id.toString()) {
            return item;
        }
    }
    return undefined;
}

export function createItem(world: World, id: number): Entity {
    const item = Items.register(world, 'item_*', id.toString(), { maxStack: 1 });
    item.add(new Sprite(ITEM_SPRITE[id]));
    return item;
}

export function createItems(world: World) {
    for (let id = 0; id < ITEM_SPRITE.length; id++) {
        createItem(world, id);
    }
}

export function spawnItem(world: World, id: number, count: number, x: number, y: number): Entity {
    const item = findItem(world, id) ?? createItem(world, id);

    item.add(new Position(x, y));
    item.add(new PickupCount(count));

    return item;
}
