
/** @const @type {number} */
var POLL_INTERVAL = 5000;

function doGet(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(e) {
        if (xhr.readyState === 4) {
            var resp = null;

            if (xhr.status === 200) {
                resp = xhr.response;
                try {
                    resp = JSON.parse(/** @type {string} */ (resp));
                } catch (e) {
                    resp = null;
                }
            }
            callback(xhr.status, resp);
        }
    };
    xhr.open('GET', url, true);
    xhr.send(null);
}

function initPolling() {
    lazyGetPseudonyme(function(pseudo) {
        if (pseudo) {
            doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
                if (resp) {
                    GRID = new Grid(resp, pseudo);
                    if (resp["players"]) {
                        GRID.updatePlayers(resp["players"]);
                        if (!GRID.playerSelf)
                            GRID.playerSelf = GRID.players[GRID.playerSelfId];
                        onPlayersUpdated();
                    }
                    if (resp["grid"]) {
                        GRID.update(resp["grid"]);
                        uiCreateGrid();
                    }
                    if (resp["gridTime"]) {
                        GRID.gridTime = parseInt(resp["gridTime"], 10);
                    } else {
                        scheduleNextPoll();
                    }
                    KNOWN_VERSION = Math.max(KNOWN_VERSION, resp["v"] || 0);
                } // TODO else cannot init party
            });
        } // TODO else cannot init pseudo
    });
}

function pollNow() {
    if (pollNow.polling !== true) {
        if (pollNow.pollSchedule) {
            clearTimeout(pollNow.pollSchedule);
            pollNow.pollSchedule = 0;
        }
        pollNow.polling = true;
        doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(status, resp) {
            if (pollNow.stopped !== true) {
                //TODO manage network error
                pollNow.polling = false;
                if (resp) {
                    updateOnPollResult(resp);
                }
                scheduleNextPoll();
            }
        });
    }
}

function stopPolling() {
    pollNow.stopped = true;
    if (pollNow.pollSchedule) {
        clearTimeout(pollNow.pollSchedule);
        pollNow.pollSchedule = 0;
    }
    console.log("stop polling");
}

function scheduleNextPoll() {
    pollNow.stopped = false;
    if (!pollNow.pollSchedule)
        pollNow.pollSchedule = setInterval(pollNow, POLL_INTERVAL);
};

