/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2026 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/

import { PacketC, TileIndex } from "../protocol.ts";
import { System } from "../system.ts";
import { MapLayer } from "./mod.ts";
import { ItemData } from "./item.ts";
import { V2 } from "../util.ts";
import { SSprites } from "./sprites.ts";

export interface ItemSlot {
    item?: ItemData,
}
export interface TileData extends ItemSlot {
    x: number, y: number // tile position
    position: V2, // center position
    parts: TileIndex[]
}

export class SMapTiles extends System implements MapLayer {
    tiles: Map<string, TileData> = new Map()

    constructor(public ss: SSprites) { super() }

    override packet(p: PacketC): void {
        if (p.type == "update_map") {
            for (const [pos, parts] of p.changes) {
                this.tiles.set(pos.toString(), {
                    x: pos[0],
                    y: pos[1],
                    position: { x: pos[0] + 0.5, y: pos[1] + 0.5 },
                    parts
                })
                if (!parts.length)
                    this.tiles.delete(pos.toString())
            }
        }
    }

    draw_map_layer(ctx: CanvasRenderingContext2D): void {
        for (const [_, tile] of this.tiles) {
            ctx.save()
            ctx.translate(tile.x + 0.5, tile.y + 0.5)
            for (const p of tile.parts)
                this.ss.draw_tile(ctx, p)
            ctx.restore()

        }
    }
}
