
const http = require('http')
    ,util = require('util')
    ,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'

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) {
    const todayymmdd = (function() {
        const now = new Date()
            ,month = now.getMonth() +1
            ,day = now.getDate();
        return parseInt('' +(now.getFullYear() - 2000) +(month < 10 ? '0' : '') +month +(day < 10 ? '0' : '') +day);
    })();
    getVar(RCILIST, (grids) => {
        if (grids) {
            let gridObjects = [];
            for (let gridId in grids) {
                let gridDate = parseInt(gridId.substr(4, 2) +gridId.substr(2, 2) +gridId.substr(0, 2), 10);
                if (gridDate <= todayymmdd) {
                    gridObjects.push({
                        "id": gridId
                        ,"date": gridDate
                        ,"provider": "20 minutes"
                        ,"level": parseInt(grids[gridId][1], 10)
                    });
                }
            }
            cb(gridObjects);
        } else {
            cb(null);
        }
    });
};

module.exports.createGrid = function(gridPublicId, gridId, cb) {
    console.log("[gridManager] get grid " +gridId);
    getVar(util.format(RCIGETGRID, gridId), (data) => {
        if (data) {
            cb(new Grid(gridPublicId, data));
        } else {
            cb(null);
        }
    });
};

