/src/mapview.ts
import gs from './gamestate';
import { Cell } from './cell';
import { Direction } from './direction';

const MAP_WIDTH = 9;
const MAP_HEIGHT = 9;
const nullCell = new Cell(-1, -1);

export default class MapView {
    root: HTMLDivElement
    coords: HTMLDivElement
    cells: HTMLDivElement[][]

    constructor() {
        this.root = <HTMLDivElement>document.getElementById('mapview');
        this.coords = <HTMLDivElement>document.getElementById('coords');

        this.cells = [];
        for (let j = 0; j < MAP_HEIGHT; j++) {
            const row = document.createElement('div');
            this.cells[j] = [];

            for (let i = 0; i < MAP_WIDTH; i++) {
                const cell: HTMLDivElement = document.createElement('div');
                cell.className = 'map-cell';
                row.appendChild(cell);
                this.cells[j][i] = cell;
            }

            this.root.appendChild(row);
        }
    }

/* 012345678
   1
   2
   3
   3
   4   P
   5
   6
   7
   8
*/

    updateAll() {
        const [ px, py ] = gs.map.getPlayerPosition();

        for (let j = py - 4; j <= py + 4; j++) {
            for (let i = px - 4; i <= px + 4; i++) {
                this.update(i, j);
            }
        }
        gs.mapView.updateCoords(px, py);
    }

    update(x: number, y: number) {
        const [ px, py ] = gs.map.getPlayerPosition();
        const cx = x - px + 4;
        const cy = y - py + 4;
        if (cx < 0 || cy < 0 || cx >= MAP_WIDTH || cx >= MAP_HEIGHT)
            return;
        const cell = (x < 0 || y < 0 || x >= gs.map.width || y >= gs.map.height) ?
            nullCell :
            gs.map.cells[y][x];
        const domCell = this.cells[cy][cx];

        let visual = null;

        domCell.classList.toggle('navigable', cell.navigable);
        domCell.classList.toggle('blocked-n', !cell.exits[Direction.North]);
        domCell.classList.toggle('blocked-e', !cell.exits[Direction.East]);
        domCell.classList.toggle('blocked-s', !cell.exits[Direction.South]);
        domCell.classList.toggle('blocked-w', !cell.exits[Direction.West]);

        if (x == px && y == py) {
            visual = '\u25CF';
        }

        domCell.innerText = visual;
    }

    updateCoords(x: number, y: number) {
        this.coords.innerText = '[' + x +  ', ' + y + ']';
    }
}