/**
 * smtp-email.js
 * Copyright (c) 2000 - 2015 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 async = require('async');
var path = require('path');
var fs = require('fs');

var Installer = require('../installer.js');
var dibs = require('../../../core/dibs.js');
var utils = require('../../../lib/utils.js');
var Tutils = require('../../org.tizen.common/tizen_utils.js');


module.exports.executeEvent = executeEvent;

/**
 * Execute evnet
 *  - install windows toolchain pachage
 * @function executeEventForServer
 * @param {module:models/job~Job} job - job
 * @param {string} workspace - workspace
 * @param {module:lib/utils.callback_error} callback - callback(error)
 * @memberOf module:models/tizen-project/install-windows-toolchain
 *  @param {
 */
function executeEvent(property, job, monitor, options, callback) {
    var workspacePath = options.workspacePath;
    var workspaceTempPath = options.workspaceTempPath;
    var environments = options.environments;

    var host = Tutils.getHost(environments);
    var hostOS = host.os;

    if (hostOS && Tutils.getOSCategory(hostOS) !== 'windows') {
        monitor.updateProgress('*Install windows toolchain package*');
        return callback(null);
    }

    var workspaceTempDir = workspaceTempPath;
    var toolchainShareDir = path.join(workspacePath, 'share', job.distName, property.PKG_NAME);
    var toolchainInfoPath = path.join(toolchainShareDir, 'dibs_toolchain.json');
    var packageName = property.PKG_NAME;

    async.waterfall([
        function (cb) {
            monitor.updateProgress('*Install windows toolchain package*', cb);
        }, function (cb) {
            var repo = dibs.getServersByType('repo')[0];
            job.board.push({
                type: 'STMP',
                time: utils.getTimeString(),
                name: 'Install windows toolchain package'
            });

            var installOpts = { extractCacheDir: workspaceTempDir };
            if (job.distribution && job.distribution.options && job.distribution.options.PARENT_REPO_URL) {
                installOpts.parentRepoURL = job.distribution.options.PARENT_REPO_URL;
            }

            Installer.installMultiplePackages([{name: packageName, os: hostOS}],
                                              toolchainShareDir, repo, job.distName, host, installOpts, monitor, cb);
        }, function (cb) {
            monitor.updateProgress('Install ' + packageName + '[' + hostOS + ' ]' + ' package... done', cb);
        }, function (cb) {
            // get toolchain information
            if (fs.existsSync(toolchainInfoPath) && fs.lstatSync(toolchainInfoPath).isFile()) {
                var toolchainInfo = createJson(toolchainInfoPath);
                if (toolchainInfo) {
                    // set toolchain information
                    var info = {
                        PACKAGE: packageName,
                        BIN_PATH: toolchainInfo.BIN_PATH || null,
                        CMD_PATH: toolchainInfo.CMD_PATH,
                        TOOLCHAIN_PATH: toolchainShareDir
                    };
                    job.options.TOOLCHAIN = info;
                    monitor.updateProgress('Get toolchain information from \'dibs_toolchain.json\'... done', cb);
                } else {
                    return cb(new Error('Cannot read ' + toolchainInfoPath + ' file.'));
                }
            } else {
                return cb(new Error('Cannot found ' + toolchainInfoPath + ' file.'));
            }
        }], callback);
}

function createJson(jsonPath) {
    var j = require(jsonPath);
    // verify format
    if (j.CMD_PATH === undefined || typeof j.CMD_PATH !== 'string') {
        return null;
    }
    return j;
}
