
var _          = require('lodash');
var fs         = require('fs');
var fse        = require('fs-extra');
var path       = require('path');
var archiver   = require('archiver');
var unzip      = require('node-unzip-2');


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

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

//
// Resource Directories
//
const reportDataDir       = app.getPath('documents') + '/IOLab-WorkFiles/reports/';
const reportImportDataDir = app.getPath('documents') + '/IOLab-WorkFiles/reports/import/';


//
// Export feature
//
ipc.on('export', function(event, type, dataID) {
    console.log('ipc args', type, dataID);

    var options = {
        defaultPath: app.getPath('documents'),
        filters: [ { name: 'Lab', extensions: ['lab']} ]
    };

    var callback = function (fileName) {
        if (!fileName) return;

        var archive = archiver('zip');
        var output = fs.createWriteStream(fileName);

        output.on('close', function() {
            event.sender.send('export-reply', {
                type: type,
                dataID: dataID,
                size: archive.pointer()
            });
            console.log(archive.pointer() + ' total bytes');
            console.log('archiver has been finalized and the output file descriptor has closed.');
        });

        archive.on('error', function(err) {
            throw err;
        });

        archive.pipe(output);

        var metaDataFile = dataID + '.bson';

        if (!fs.existsSync(reportDataDir + metaDataFile)) {
            throw new Error('There is not bson file ' + reportDataDir + metaDataFile);
        }

        if (!fs.existsSync(reportDataDir + dataID)) {
            archive
                .file(reportDataDir + metaDataFile, { name: metaDataFile })
                .finalize();
            return;
        }

        archive
            .file(reportDataDir + metaDataFile, { name: metaDataFile })
            .directory(reportDataDir + dataID, '/' + dataID)
            .finalize();

    };

    dialog.showSaveDialog(iolabWindow.window, options, callback);
});

//
// Import
//
ipc.on('import', function(event, type) {

    var options = {
        defaultPath: app.getPath('documents'),
        filters: [ { name: 'Lab', extensions: ['lab']} ]
    };

    var callback = function(fileName) {
        if (!fileName) return;

        fse.removeSync(reportImportDataDir);
        fs.mkdirSync(reportImportDataDir);

        fs.createReadStream(fileName[0])
            .pipe(unzip.Extract({path: reportImportDataDir}))
            .on('error', function(err) {
                throw err;
            })
            .on('close', function () {

                console.log('unzip ok');
                console.log('unzip files', fs.readdirSync(reportImportDataDir));

                var bson,
                    bsonFile = _.find(fs.readdirSync(reportImportDataDir), function (file) {
                        return file.indexOf('.bson') > -1;
                    });

                if (bsonFile) {
                    bson = fs.readFileSync(reportImportDataDir + '/' + bsonFile);

                    event.sender.send('import-reply', { bson: bson });

                } else {
                    throw new Error('There is not bson file in the "lab" archive');
                }
            });

    };

    dialog.showOpenDialog(iolabWindow.window, options, callback);
});

ipc.on('confirm-import', function(event, type, ID) {
    if (!fs.existsSync(reportImportDataDir + '/' + ID + '.bson')) {
        throw new Error('The report with id ' + ID + ' cannot be found.');
    }

    fse.copySync(reportImportDataDir, reportDataDir);
    fse.removeSync(reportImportDataDir);

    event.sender.send('confirm-import-reply');
});