
var GRID_PUBLIC_ID
    ,KNOWN_VERSION = 0
    ,GRID

    ,SELECTED = []
    ,CURRENTINPUT = null;

function lazyGetPseudonyme(cb) {
    var pseudo = window["sessionStorage"].getItem("pseudonyme_" +GRID_PUBLIC_ID);
    if (pseudo) {
        cb(pseudo);
    } else {
        doGet("/api/register?grid=" +GRID_PUBLIC_ID, function(status, pseudo) {
            if (status && pseudo) {
                window["sessionStorage"].setItem("pseudonyme_" +GRID_PUBLIC_ID, pseudo);
                cb(pseudo);
            } else {
                cb(null);
            }
        });
    }
}

function keyPressHandler(cell, key) {
    cell.dom.classList.add(R.klass.cell.pending);
    doGet("/api/put?grid=" +GRID_PUBLIC_ID +"&key=" +key +"&x=" +cell.x +"&y=" +cell.y +"&me=" +GRID.playerSelf.idEncoded, function(status, resp) {
        cell.dom.classList.remove(R.klass.cell.pending);
        if (status === 403 && !cell.data.found) {
            cell.dom.classList.add(R.klass.cell.wrong);

        } else if (status === 204) {
            pollNow();

        } else {
            // out of sync ?
            pollNow();

        }
    });
}

function updateOnPollResult(resp) {
    if (resp["players"]) {
        GRID.updatePlayers(resp["players"]);
        if (!GRID.playerSelf)
            GRID.playerSelf = GRID.players[GRID.playerSelfId];
        onPlayersUpdated();
    }
    if (resp["grid"]) {
        GRID.update(resp["grid"]);
        onGridUpdated();
    }
    if (resp["gridTime"]) {
        GRID.gridTime = parseInt(resp["gridTime"], 10);
        stopPolling();
    }
    KNOWN_VERSION = Math.max(KNOWN_VERSION, resp["v"] || 0);
}

function unselect() {
    SELECTED.forEach(function (cell) {
        cell.dom.classList.remove(R.klass.cell.selected);
    });
    if (CURRENTINPUT) {
        CURRENTINPUT.dom.classList.remove(R.klass.cell.currentInput);
        CURRENTINPUT = null;
    }
    SELECTED = [];
}

function select(x, y) {
    var cell = UI_CELLS[x +y *GRID.width];
    SELECTED.push(cell);
    cell.dom.classList.add(R.klass.cell.selected);
}

document.addEventListener('DOMContentLoaded', function() {
    GRID_PUBLIC_ID = (document.location.hash.substr(1));

    if (GRID_PUBLIC_ID == "") {
        document.location.href = "/";
        return;
    }

    document.addEventListener('click', gridClickDelegate);
    document.addEventListener('keydown', function(e) {
        if (e.key.toUpperCase() === 'BACKSPACE') {
            e.preventDefault();
        }
    });
    document.addEventListener('keyup', function(e) {
        if (CURRENTINPUT && !CURRENTINPUT.data.found) {
            if (e.key.toUpperCase() == "DELETE") {
                CURRENTINPUT.dom.classList.remove(R.klass.cell.wrong);
                CURRENTINPUT.data.letter = null;
                onGridUpdated();
            } else if (e.key.toUpperCase() == "BACKSPACE") {
                CURRENTINPUT.dom.classList.remove(R.klass.cell.wrong);
                CURRENTINPUT.data.letter = null;
                uiSelectWritableCell(-1);
                onGridUpdated();
            } else if (e.key.length === 1) {
                var key = e.key.charAt(0).toUpperCase();
                if (key.match(/[A-Z]/)) {
                    CURRENTINPUT.data.letter = key;
                    keyPressHandler(CURRENTINPUT, key);
                    onGridUpdated();
                    uiSelectWritableCell(1);
                }
            } // TODO catch arrow keys
        }
    });
    initPolling();
});

