console.log('*** IOLab Electron ***');
console.log('Node version', process.version);

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');

//
// Debug shortcut
//
//require('electron-debug')({ showDevTools: false });

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

global.iolabVersion = iolabPackage.version;

//
// Create an instance of iolab
//
function iolabCallback (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);
}

const iolab = require('iolab-node/lib').IOLabNode(iolabCallback);

//
// IPC communication
//

// IOLab
ipc.on('iolab', function(event, cmd, ipcId, args) {
    if (!iolab) 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 = iolab[cmd](args) || {};

    if (!ipcId) return;

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

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

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

//
// Application event
//

// 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;

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

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

app.on('ready', function() {

    // Protocols registration
    require('./browser/protocols');
    require('./browser/menu')();

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