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

var Monitor = require('../../../lib/monitor.js');
var TsRepo = require('../../org.tizen.ts.cli.repository/ts-repo.js');
var util = require('../../org.tizen.ts.base.common/util.js');

module.exports.download = function (argv, log) {
    var repoLocation = argv.r;
    var packageList = argv.P;
    var hostOs = util.getTargetOS(os.platform(), os.arch());
    var targetOS = argv.os || hostOs.os;
    var baseSnapshot = argv.b;

    var monitor = new Monitor({
        onProgress: function (info, cb) {
            if (info.logType) {
                log[info.logType](info.log);
            }
            cb(null);
        }
    });

    if (!repoLocation) {
        log.error('Required --repository option!');
        log.error('Usage: ts-cli download --repository <repository path> --package <package file path|list> [--os <os name | all>] [--base-snapshot <snapshot name>]');
        process.exit(-1);
    }

    if (!packageList) {
        log.error('Required --package option!');
        log.error('Usage: ts-cli download --repository <repository path> --package <package file path|list> [--os <os name | all>] [--base-snapshot <snapshot name>]');
        process.exit(-1);
    } else {
        packageList = packageList.split(',');
    }

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

    log.info('Tizen Studio Download Package Process - Start');

    async.waterfall([
        function (cb) {
            if (repository.isRemoteRepo) {
                return cb(null);
            } else {
                fs.access(repoLocation, function (err) {
                    if (err) {
                        return cb('not found repository');
                    } else {
                        return cb(null);
                    }
                });
            }
        }, function (cb) {
            // open repository
            log.info(' # - Open repostiory ' + repoLocation);
            repository.load(function (err) {
                if (err) {
                    return cb(err);
                } else {
                    var distribution = repository.distributions[repository.distName];
                    if (distribution) {
                        return cb(null, distribution);
                    } else {
                        return cb('Not found distribution.');
                    }
                }
            });
        }, function (distribution, cb) {
            if (baseSnapshot) {
                log.info(' # - Search Snapshot ' + baseSnapshot);
                distribution.searchSnapshots({name: baseSnapshot}, function (err, snapshots) {
                    if (err) {
                        return cb(err);
                    } else {
                        return cb(null, distribution, snapshots[0]);
                    }
                });
            } else {
                return cb(null, distribution, distribution.latestSnapshot);
            }
        }, function (distribution, snapshot, cb) {
            if (!snapshot) {
                return cb('Failed get snapshot ' + baseSnapshot);
            }

            getPackages(snapshot, packageList, targetOS, function (err, packages) {
                cb(err, distribution, snapshot, packages);
            });
        }, function (distribution, snapshot, packages, cb) {
            snapshot.downloadPackages(distribution.path, packages, process.cwd(), monitor, cb);
        }
    ], function (err) {
        if (err) {
            log.error('Package download - Failure!');
            log.error(err);
            process.exit(-1);
        } else {
            log.info('Package download - Success');
            process.exit(0);
        }
    });
};

function getPackages(snapshot, packageList, targetOS, callback) {
    var packages = [];

    for (var i = 0; i < packageList.length; i++) {
        var pkgName = packageList[i];

        if (snapshot.archivePackages.indexOf(pkgName) !== -1) {
            packages.push(pkgName);
        } else if (snapshot.osPackages[targetOS] && snapshot.osPackages[targetOS][pkgName]) {
            packages.push(snapshot.osPackages[targetOS][pkgName]);
        } else {
            return callback('Not found package - ' + pkgName);
        }
    }
    callback(null, packages);
}
