/**
 * util.js
 * Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * Sungmin Kim <sm.art.kim@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 util = require('util');
var path = require('path');
var os = require('os');

var utilPackage = require('./util-package.js');
var Process = require('../dibs.core/process.js');

util.getTargetOS = getTargetOS;
util.getOSCategory = getOSCategory;
util.checkCancelBeforeCallback = checkCancelBeforeCallback;
util.extractPackageFile = extractPackageFile;
util.knownFileExtensions = knownFileExtensions;
util.package = utilPackage;

module.exports = util;

/**
 * @function getTargetOS
 * @param {string} platform
 * @param {string} arch
 * @returns {object}
 * @memberOf module:models/tizen-common/tizenUtils
 */

function getTargetOS(platform, arch) {
    var result = {};
    var archNum = arch.replace(/[^0-9]/g, '');
    if (archNum.length !== 2) {
        return result;
    }

    switch (platform.toLowerCase()) {
    case 'linux':
        result = {
            os: 'ubuntu-' + archNum,
            category: 'linux'
        };
        break;
    case 'win32':
        result = {
            os: 'windows-' + archNum,
            category: 'windows'
        };
        break;
    case 'darwin':
        result = {
            os: 'macos-' + archNum,
            category: 'macos'
        };
        break;
    default :
        result = {};
    }
    return result;
}

/**
 * @function getOSCategory
 * @param {string} os
 * @returns {string}
 * @memberOf module:models/tizen-common/tizenUtils
 */
function getOSCategory(os) {
    if (os) {
        if (os.indexOf('ubuntu') >= 0 || os.indexOf('Ubuntu') >= 0) {
            return 'linux';
        }
        if (os.indexOf('windows') >= 0 || os.indexOf('Windows') >= 0) {
            return 'windows';
        }
        if (os.indexOf('macos') >= 0 || os.indexOf('MacOS') >= 0 || os.indexOf('OSX') >= 0) {
            return 'macos';
        }
    } else {
        return '';
    }
}


function checkCancelBeforeCallback(job) {
    return function () {
        if (job && job.canceled === true) {
            var error = new Error('job #' + job.id + ' is canceled !!');
            arguments[arguments.length - 1].apply(null, [error]);
            return;
        }
        var args = Array.prototype.slice.call(arguments, 0);
        args.pop();
        args.unshift(null);
        arguments[arguments.length - 1].apply(null, args);
    };
}


function extractPackageFile(pkgFile, targetDir, options) {
    var ext = path.extname(pkgFile);
    var cmd = null;
    var args = [];
    switch (ext) {
    case '.zip':
        if (os.platform() === 'win32') {
            cmd = '7z';
            if (options.targetFile) {
                args = ['x', '-o' + targetDir, pkgFile, options.targetFile];
            } else {
                args = ['x', '-o' + targetDir, pkgFile];
            }
        } else {
            cmd = 'unzip';
            if (options.targetFile) {
                args = ['-o', pkgFile, options.targetFile, '-d', targetDir];
            } else {
                args = ['-o', pkgFile, '-d', targetDir];
            }
        }
        break;
    case '.tar':
        cmd = 'tar';
        args = ['-xf', pkgFile, '-C', targetDir];
        break;
    default:
        return null;
    }


    return Process.create(cmd, args, {
        cwd: process.cwd(),
        env: process.env
    }, {
        onStdout: options.onStdout,
        onStderr: options.onStderr,
        onExit: options.onExit
    });
}

function knownFileExtensions() {
    return ['.zip', '.tar', '.7z', '.gzip', '.gz'];
}
