/// <reference path="../../World/Classes/Action/ActionRetrace.ts" />
/// <reference path="../../World/Classes/Action/ActionGo.ts" />
/// <reference path="../../Controls/Modules/Links.ts" />
/// <reference path="../Elements.ts" />
/// <reference path="HoverInfo.ts" />
/// <reference path="../Classes/RoomNode.ts" />
module Elements.RememberedHandler {
    //var target = document.getElementById("rememberedRoomsTarget");
    var mapTarget = document.getElementById("mapTarget");
    var lastMap : RoomRandomMap;
    var elements : { [xy : string] : RoomNode};

    export function empty () {
        // while (target.firstChild) {
        //     target.removeChild(target.firstChild);
        // }

        elements = {};
        lastMap = undefined;

        while (mapTarget.firstChild) {
            mapTarget.removeChild(mapTarget.firstChild);
        }
    }

    export async function updateMap () {
        console.debug(Rulebook.getIndentation() + "[MAP] Creating Map");

        let regions = Region.InRelation.getAllLeftType(WorldState.player.getRoom(), RegionRandom);
        let biggestRegion = <RegionRandom> regions[regions.length - 1];
        if (biggestRegion == undefined) {
            empty();
            return;
        }

        if (biggestRegion.map != lastMap) {
            empty();
        } else {
            await updateOldMap();
            return;
        }

        let map = biggestRegion.map;
        lastMap = map;

        map.updateAllLimits();

        for (let y = map.highestY; y >= map.lowestY; y--) {
            let row = document.createElement("div");
            row.classList.add("mapRow");
            for (let x = map.lowestX; x <= map.highestX; x++) {
                let room = map.getRoom(x, y);
                let roomNode = new RoomNode(room);
                await roomNode.createRoomNameFloater();

                let roomDiv = roomNode.getElement();
                row.appendChild(roomDiv);

                elements[x.toString() + ";" + y.toString()] = roomNode;
            }
            mapTarget.appendChild(row);
        }

        await updateOldMap();
    }

    export async function updateOldMap () {
        let map = lastMap;
        for (let y = map.highestY; y >= map.lowestY; y--) {
            for (let x = map.lowestX; x <= map.highestX; x++) {
                await elements[x.toString() + ";" + y.toString()].update();
            }
        }
    }
}