/**
 * ts-archive-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
**/

'use strict';

var async = require('async');
var fs = require('fs');
var Monitor = require('../../lib/monitor.js');
var path = require('path');
var os = require('os');

module.exports = TsArchiveJob;

function TsArchiveJob(options) {
    this.name = options.name;
    this.type = 'Tizen-Archive';
    this.filename = options.filename;
    this.path = options.path;
    this.log = options.log || console;
    this.buildRoot = options.buildRoot || path.join(os.tmpdir(), 'ts-cli', this.name);
}

TsArchiveJob.prototype.build = build;

function build(repo, opts, callback) {
    var self = this;

    self.log.info('Start Build - ' + self.name);
    var monitor = new Monitor({
        onProgress: function (info, cb) {
            if (info.logType) {
                self.log[info.logType](info.log);
            }
            cb(null);
        }
    });

    var dist = repo.distributions[repo.distName];
    if (!dist) {
        return callback(new Error('# - Failed to get \'' + repo.distName + '\''));
    }


    async.series([
        function (cb) {
            fs.access(self.path, cb);
        },
        function (cb) {
            if (opts.push) {
                dist.registerPackages([self.path], { force: opts.force}, monitor, cb);
            } else {
                cb(null);
            }
        }
    ],
    function (err) {
        callback(err);
    });
}
