/**
 * dpkg-cli.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

var optimist = require('optimist');
var os = require('os');
var path = require('path');

var dibs = require('../../core/dibs.js');
var Installer = require('./pkg-installer.js');
var Monitor = require('../../lib/monitor.js');


// option parse & set
var argv = optimist.usage(
    'Usage: dpkg-cli SUBCOMMAND [OPTS] or $0 (-h|-v)' + os.EOL +
    'Subcommands:' + os.EOL +
    '    install         Install DIBS packages/plugins.' + os.EOL +
    '    uninstall       Remove DIBS packages/plugins.' + os.EOL +
    os.EOL +
    'Subcommand usage:' + os.EOL +
    '    dpkg-cli install -P <package list> [-l <location>] [--force]' + os.EOL +
    '    dpkg-cli uninstall -P <package list> [-l <location>]' + os.EOL
).alias({
    P: 'pkgs',
    l: 'loc',
    h: 'help'
})
    .string(['P', 'l'])
    .describe('P', 'package/plugin name or path list')
    .describe('l', 'install location')
    .describe('force', 'install/uninstall forcely')
    .describe('h', 'display help')
    .argv;

var subCmds = argv._;

if (argv.h) {
    optimist.showHelp();
    process.exit(0);
}

if (!subCmds || subCmds.length === 0) {
    console.error('Sub-Command must be specified!');
    process.exit(-1);
}


// init variables
var pkgListString = argv.P;
var installLocation = argv.l;

var options = {};
if (argv.force) {
    options.force = true;
}

// init
dibs.initialize();

// prepare monitor
var monitor = new Monitor({
    onProgress: function (info, cb) {
        if (info.logType && (info.logType === 'error' || info.logType === 'warn')) {
            console.log('(' + info.logType + ') ' + info.log);
        } else {
            console.log(info.log);
        }
    }
});


switch (subCmds[0]) {
case 'install':
    handle_install_command(pkgListString, installLocation, options, monitor);
    break;
case 'uninstall':
    handle_uninstall_command(pkgListString, installLocation, options, monitor);
    break;
default:
    console.error('Invalid sub-command!: \'' + subCmd + '\'');
    process.exit(-1);
}


function handle_install_command(pkgPathList, installPath, options, monitor) {

    // check arguments
    if (!pkgPathList || pkgPathList.length === 0) {
        console.error('Package file(s) or name(s) MUST be specified!');
        process.exit(-1);
    }

    // parse package files
    var filePathList = pkgPathList.split(',').filter(function (e) {
        return e.indexOf('.') !== -1;
    }).map(function (e) {
        return e.indexOf('.') === 0 ?
            path.resolve(process.cwd(), e) :
            path.resolve(e);
    });

    Installer.installPackages(filePathList, installPath, options, monitor, function (err) {
        if (err) {
            console.error(err);
            console.error('Installing package(s) failed!');
        } else {
            console.log('Installing packages(s) succeeded!');
        }
    });
}


function handle_uninstall_command(pkgNameList, installPath, options, monitor) {

    if (!pkgNameList || pkgNameList.length === 0) {
        console.error('Package name(s) MUST be specified!');
        process.exit(-1);
    }

    // parse package names
    pkgNameList = pkgNameList.split(',');

    Installer.uninstallPackages(pkgNameList, installPath, monitor, function (err) {
        if (err) {
            console.error(err);
            console.error('Uninstalling package(s) failed!');
        } else {
            console.log('Uninstalling packages(s) succeeded!');
        }
    });
}

