import { Color, MAP_HEIGHT, MAP_ROOM_CHARS, MAP_WIDTH, MAP_X, MAP_Y } from "./const";
import { drawBox, setChar } from "./display";
import { Drawable } from "./drawable";
import { getRoomsForLayer, Room } from "./room";

export class GameMap extends Drawable {
    constructor(public currentRoom: Room) {
        super();
    }

    override doDraw() {
        drawBox(MAP_X, MAP_Y, MAP_WIDTH - 2, MAP_HEIGHT - 2, { fill: [' '], title: 'Map' });
        const centerX = this.currentRoom.worldX - MAP_X - MAP_WIDTH / 2;
        const centerY = this.currentRoom.worldY - MAP_Y - MAP_HEIGHT / 2;

        for (const room of getRoomsForLayer(this.currentRoom.worldZ)) {
            const x = Math.round(room.worldX - centerX);
            const y = Math.round(room.worldY - centerY);

            if (x > MAP_X && x < MAP_X + MAP_WIDTH - 1 && y > MAP_Y && y < MAP_Y + MAP_HEIGHT - 1) {
                const char = getMapRoomChar(room);
                setChar(x, y, [char, room === this.currentRoom ? Color.YELLOW : Color.WHITE]);
            }
        }
    }
}

function getMapRoomChar(room: Room): string {
    let doorsMask = 0;
    for (let i = 0; i < 4; i++) {
        const mask = 1 << i;
        if (room.doors[i]) {
            doorsMask |= mask;
        }
    }

    return MAP_ROOM_CHARS[doorsMask];
}
