
const http = require('http')
    ,util = require('util')
    ,crypto = require('crypto')
    ,Grid = require('./Grid.js').Grid;

const RCILIST = 'http://rcijeux.fr/drupal_game/20minutes/menu/js/jeux_mfleches.js?date=1495635261516'
    ,RCIGETGRID = 'http://rcijeux.fr/drupal_game/20minutes/grids/%s.mfj'
    ,DEBUG_QUERY = true
    ,CACHE_EXPIRACY = 86400000; // 1 day

const GRID_CACHE = {
    data: {},
    expireAt: 0
}
    ,GRID_DATA = {}; // TODO expiracy

function extractVar(data) {
    var first = data.indexOf('{')
        ,last = data.indexOf('}');

    if (first == -1 || last == -1 || last < first)
        return null;
    try {
        var dataObj;
        eval("dataObj="+data.substr(first, last));
        return dataObj;
    } catch (e) {
        return null;
    }
    return null; // unreachable
}

function getVar(url, cb) {
    http.get(url, (res) => {
        let chunks = null;
        res.on('data', (chunk) => {
            if (chunks)
                chunks = Buffer.concat([chunks, chunk], chunks.length +chunk.length);
            else
                chunks = Buffer.from(chunk);
        });
        res.once('end', () => {
            cb(extractVar(chunks.toString("utf8")));
        });
    });
}

module.exports.listGrids = function(cb) {
    if (DEBUG_QUERY) {
        console.warn("[gridManager] debug skip list grids");
        cb({"240517":{ level: '1' }});
    } else {
        const now = Date.now();

        if (GRID_CACHE.expireAt < now) {
            console.log("[gridManager] list grids");
            getVar(RCILIST, (grids) => {
                if (grids) {
                    let gridObjects = {};
                    for (let gridId in grids) {
                        gridObjects[gridId] = {
                            "level": grids[gridId][1]
                        };
                    }
                    GRID_CACHE.data = gridObjects;
                    GRID_CACHE.expireAt = now +CACHE_EXPIRACY;
                    cb(gridObjects);
                } else {
                    cb(null);
                }
            });
        } else {
            cb(GRID_CACHE.data);
        }
    }
};

module.exports.createGrid = function(gridPublicId, gridId, cb) {
    console.log("[gridManager] get grid " +gridId);
    // FIXME DEBUG
    var grid = GRID_DATA[gridPublicId] = new Grid(gridPublicId, require('../test.js'));
    cb(grid);
    return;
    // END DEBUG
    getVar(util.format(RCIGETGRID, gridId), (data) => {
        if (data) {
            var grid = GRID_DATA[gridPublicId] = new Grid(gridPublicId, data);
            cb(grid);
        } else {
            cb(null);
        }
    });
};

module.exports.get = function(gridPublicId) {
    return GRID_DATA[gridPublicId] || null;
};

module.exports.hash = function(toHash) {
    var md5sum = crypto.createHash('sha1');
    md5sum.update(toHash);
    return md5sum.digest('base64');
};

