/**
 * ts-build.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 path = require('path');

var TsRepo = require('../../org.tizen.ts.cli.repository/ts-repo.js');
var TsJob = require('../../org.tizen.ts.cli.projects/ts-job.js');

module.exports.build = function (argv, log) {
    var clean = argv.c;
    var repository = argv.r;
    var cwd = argv.s;
    var force = argv.f;
    var push = argv.p;

    if (!repository) {
        log.error('Usage: ts-cli build --repository <repository path> [--source <source path>] [--clean] [--push [--force]]');
        process.exit(-1);
    }

    log.info('TS-CLI Build Process - Start');

    var repo = new TsRepo({
        location: repository
    });

    async.waterfall([
        function (cb) {
            repo.load(cb);
        },
        function (cb) {
            TsJob.create(path.resolve(cwd), {log: log}, cb);
        },
        function (job, cb) {
            job.build(repo, {
                log: log,
                clean: clean,
                force: force,
                push: push
            }, cb);
        }
    ], function (err) {
        if (err) {
            log.error(err);
            process.exit(-1);
        }
        process.exit(0);
    });
};
