const exec            = require('child_process').execFile;

const $config       = require('./config/config');
const web           = require('./helpers/web');
const filehelper    = require('./helpers/files');

let mainWindow      = null;

exports.init = function(win)
{
    mainWindow = win;

    if(!filehelper.fileExists('./version')) {
        filehelper.createFile('./version', 0);
        version = 0;
    } else {
        version = filehelper.loadFile('./version');
    }
    setTimeout(function() { checkVersion(); }, 1999);
};

var checkVersion = function()
{
    web.webRequest($config.api.url + '?key=' + $config.api.key + '&version=' + version, 'updater.parseRequest');
};

exports.parseRequest = function(e)
{
    var json = e.data;

    if(json.currentVersion > version && json.requiredFiles.length > 0) {
        updateFiles(json);
    } else {
        this.startApp();
    }
};

var updateFiles = function(data)
{
    //filehelper.saveFile('./version', data.currentVersion);

    var totalFiles = data.requiredFiles.length;
    var totalData  = 0;

    data.requiredFiles.forEach(function(file) {
        totalData += file.size;
    });

    for(let i = 0; i < totalFiles; i++) {
        var file = data.requiredFiles[i];
        web.downloadFile(file.url, file.name, totalData);
    }
};

exports.startApp = function()
{
    //mainWindow.close();
    //exec($config.system.executable);
};