console.log('*** IOLab Electron ***');

const _           = require('lodash');
const fs          = require('fs');
const path        = require('path');

const electron    = require('electron');
const app         = electron.app;
const ipc         = electron.ipcMain;

const iolabWindow = require('./browser/iolabWindow');
const repoWindow  = require('./browser/repoWindow');

const iolabPackage = require('./package.json');

//
// Logger (exported to Global to give access in renderer process)
//
global.logger = require('./browser/logger');

global.iolabVersion = iolabPackage.version;

//
// Create an instance of iolab
//

const iolabAPI = require('iolab-node/lib')
    .IOLabNode(function (arg) {
        var len = arg.length;
        var cmd = arg;

        // Log only the LOG, WAR and ERR
        if (arg.substr(0, 3) == '***') {
            logger.info(arg.substr(4, len - 4));
            cmd = 'console.log(\"' + arg.substr(4, len - 4) + '\")';
        }

        iolabWindow.executeJavaScript(cmd);
        repoWindow.propagateJavaScript(cmd);
    });

//
// IPC communication
//

// IOLabAPI communication
ipc.on('iolab', function(event, cmd, ipcId, args) {
    if (!iolabAPI) return;

    // Make sure the arguments passed to the api are typed array and not Buffer
    _.forEach(args, function(arg, idx) {
        if (Buffer.isBuffer(arg)) {
            args[idx] = new Uint8Array(arg);
        }
    });

    // Execute the command in the IOLabAPI
    var result = iolabAPI[cmd](args) || {};

    if (!ipcId) return;

    event.sender.send('iolab-reply', {
        ipcId: ipcId,
        bson: result.bson,
        buffer: result.buffer
    });
});

ipc.on('openIOLabRepository', function() {
    repoWindow.create({
        onCloseCallBack: function() {
            // Indicate to IOLab that we close the repository window
            iolabAPI.broadcast(['repository', JSON.stringify({ closed: true })]);
        }
    });
});

ipc.on('focusIOLabRepository', function() {
    repoWindow.focus();
});

ipc.on('iolab-cookies', function(event, cmd, cookie) {
    if (cmd == 'get') {
        iolabWindow.window.webContents.session.cookies.get(cookie, (error, cookies) => {
            global.logger.info('cookies => get ' + (cookies[0] || {}).name) ;
            event.sender.send('iolab-cookies-reply', { success: !error, cookies: cookies }); 
        });
    } else if (cmd == 'set') {
        global.logger.info('cookies => set ' + cookie.name + ' ' + cookie.value) ;
        iolabWindow.window.webContents.session.cookies.set({
                url: cookie.url || 'http://localhost',
                name: cookie.name,
                value: cookie.value,
                expirationDate: cookie.expirationDate || 1893499200000 // 01-01-2030
            }, (error) => { event.sender.send('iolab-cookies-reply', { success: !error }); });
    }
});

//
// Lab resource management (export / import)
//
require('./browser/lab');

//
// Application event
//

app.on('ready', function() {
    // Protocols registration
    require('./browser/protocols');
    require('./browser/menu')();

    // Create the main window
    iolabWindow.create();
});

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    app.quit();
});

var closingOngoing;
app.on('will-quit', function(event) {
    if (closingOngoing) { return; }

    event.preventDefault();
    closingOngoing = true;

    iolabAPI.stopDataAcquisition();
    iolabAPI.remotePowerOff([1]);
    iolabAPI.remotePowerOff([2]);
    iolabAPI.resetCallback();

    setTimeout(app.quit, 500);
});
