/**
 * project.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 fs = require('fs');
var path = require('path');
var async = require('async');

var DError = require('../../core/exception.js');
var Job = require('../../plugins/dibs.model.common/job.js');
var Process = require('../../plugins/dibs.core/process.js');

/**
 * general project plugin
 * @module models/general/project
 */

/**
 * general job
 * @constructor
 * @augments module:models/job
 * @param {module:models/job~Job} baseJob - base job object
 */
function GeneralJob(baseJob) {
    Job.copy(this, baseJob);
    this.callback = null;
}


/**
 * Create general job instance
 * @function createJob
 * @param {string} prjName - project name
 * @param {string} prjType - project type
 * @param {string} distName - distribution name
 * @param {module:models/job.options} options - job options
 * @param {module:lib/utils.callback_error} callback - callback(error)
 * @memberOf module:models/general/project
 */

function createJob(userEmail, distName, prjName, prjType, environmentName, parentId, distType, options, callback) {
    Job.create(userEmail, distName, distType, prjName, prjType, environmentName, parentId, null, options,
        function (err, newJob) {
            callback(err, new GeneralJob(newJob));
        });

}
module.exports.createJob = createJob;


/**
 * Initialize general job
 * @function initializeJob
 * @param {module:models/job~Job} job - job
 * @param {string} workDir - workDir
 * @param {module:core/base-server.BaseServer} server - server
 * @param {module:lib/utils.callback_error} callback - callback(error)
 * @memberOf module:models/tizen-project/project
 */
function initializeJob(job, options, callback) {
    var error = null;
    if (!job.options.cmd && job.status === 'INITIALIZING') {
        error = new DError('GENERALJOB001');
    }

    callback(error, job);
}
module.exports.initializeJob = initializeJob;


/**
 * Execute general job
 * - it run cmd
 * @function executeJob
 * @param {module:models/job~Job} job - job
 * @param {string} workDir - workDir
 * @param {module:core/base-server.BaseServer} server - server
 * @param {module:lib/utils.callback_error} callback - callback(error)
 * @memberOf module:models/general/project
 */

function executeJob(job, options, callback) {
    var jobWorkPath = options.jobWorkPath;
    var monitor = options.monitor;

    var builder = path.join(jobWorkPath, '.build.bat');
    var result = '';
    async.waterfall([
        // gen cmd
        function (wcb) {
            fs.writeFile(builder, job.options.cmd, wcb);
        },
        function (wcb) {
            monitor.updateProgress('Generate build scrpt ...', wcb);
        },
        function (wcb) {
            fs.chmod(builder, '0777', wcb);
        },
        function (wcb) {
            monitor.updateProgress('Build Script ...', wcb);
        },
        function (wcb) {
            var error = null;
            var build = Process.create(builder,
                [],
                {
                    cwd: jobWorkPath
                },
                {
                    onStdout: function (line) {
                        monitor.updateProgress(line); result += line;
                    },
                    onStderr: function (line) {
                        monitor.updateProgress({
                            log: line,
                            logType: 'error'
                        });
                    },
                    onExit: function (code) {
                        if (code !== 0) {
                            error = new DError('GENERALJOB002', {
                                cmd: job.options.cmd,
                                code: code
                            });
                            monitor.updateProgress({
                                log: error.message,
                                logType: 'error'
                            });
                        }
                        wcb(error);
                    }
                });
            monitor.addProcess(build);
        }
    ], function (err) {
        job.result = result;

        callback(err, job);
    });
}

module.exports.executeJob = executeJob;
