
const 
    crypto = require('crypto')
    ,GridProvider = {
        "20minutes": require('./GridProvider_20min.js')
    };

const DEBUG_QUERY = false
    ,CACHE_EXPIRACY = 86400000; // 1 day

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

setInterval(function() {
    const now = Date.now()
        ,nowExpire = now -CACHE_EXPIRACY;

    for (let i in GRID_DATA) {
        if (GRID_DATA[i].minVersion < nowExpire) {
            console.log("[GridManager] cleaning " +i);
            delete GRID_DATA[i];
        }
    }
    if (GRID_CACHE.expireAt < now) {
        GRID_CACHE.data = {};
        GRID_CACHE.expireAt = 0;
    }
}, 60 * 1000); // Every minutes clean expired grids

module.exports.listGrids = function(cb) {
    const now = Date.now();

    if (GRID_CACHE.expireAt < now) {
        console.log("[gridManager] list grids");
        const providers = Object.keys(GridProvider);
        var allGrids = [];
        var fetchProvider = function(i) {
            if (i < providers.length) {
                var providerId = providers[i];
                GridProvider[providerId].listGrids((grids) => {
                    grids.forEach((grid) => {
                        grid.providerId = providerId;
                        allGrids.push(grid);
                    });
                    fetchProvider(++i);
                });
            } else {
                GRID_CACHE.data = allGrids;
                GRID_CACHE.expireAt = now +CACHE_EXPIRACY;
                cb(allGrids);
            }
        };
        fetchProvider(0);
    } else {
        cb(GRID_CACHE.data);
    }
};

module.exports.createGrid = function(gridPublicId, gridProvider, gridId, cb) {
    console.log("[gridManager] get grid " +gridId);
    if (GridProvider[gridProvider]) {
        GridProvider[gridProvider].createGrid(gridPublicId, gridId, (grid) => {
            GRID_DATA[gridPublicId] = grid;
            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');
};

