/**
 * release.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 os = require('os');
var path = require('path');
var _ = require('underscore');

var util = require('../org.tizen.ts.base.common/util.js');
var fsDist = require('../org.tizen.ts.base.repository/lib/fs-distribution-api.js');
var webDist = require('../org.tizen.ts.base.repository/lib/web-distribution-api.js');
var image = require('../org.tizen.ts.base.release/release-image.js');
var installer = require('../org.tizen.ts.base.release/release-installer.js');
var Monitor = require('../../lib/monitor.js');
var utils = require('../../lib/utils.js');

module.exports.createInstaller = createInstaller;
module.exports.createImage = createImage;

function createInstaller(distribution, options, callback) {
    if (!distribution) {
        return callback(new Error('distribution object is not given'));
    }

    var distName = distribution.name;
    var distPath = distribution.path;
    var targetSnapshot = null;

    var log = null;
    if (options && options.log) {
        log = options.log;
    } else {
        log = console;
    }

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

    var baseRepoUrl = distPath;
    if (options && options.baseRepoUrl) {
        baseRepoUrl = options.baseRepoUrl;
    }

    var metaPkgList = null;
    if (options && options.metaPkgList) {
        if (_.isArray(options.metaPkgList)) {
            metaPkgList = options.metaPkgList;
        } else {
            metaPkgList = options.metaPkgList.split(',');
        }
    }

    var excludePkgList = null;
    if (options && options.excludePkgList) {
        if (_.isArray(options.excludePkgList)) {
            excludePkgList = options.excludePkgList;
        } else {
            excludePkgList = options.excludePkgList.split(',');
        }
    }

    var installerTitle = null;
    if (options && options.installerTitle) {
        installerTitle = options.installerTitle;
    }

    var outputName = null;
    if (options && options.outputName) {
        outputName = options.outputName;
    }

    var snapshotName = null;
    if (options && options.baseSnapshot) {
        snapshotName = options.baseSnapshot;
    }

    async.waterfall([
        function (cb) {
            // get latest snapshot
            log.info(' # - Get latest snapshot ');
            distribution.searchSnapshots({ distPath: distPath, name: snapshotName }, function (err, snapshots) {
                if (!err) {
                    if (snapshots.length === 0) {
                        err = new Error('# - Any snapshot does not exist in \'' + distName + '\'');
                    } else {
                        targetSnapshot = snapshots[0];
                    }
                } else {
                    log.error(err);
                }
                cb(err);
            });
        },
        function (cb) {
            var snapshotPath = null;
            var osInfoPath = null;

            if (utils.isURL(distPath)) {
                snapshotPath = distPath + '/' + targetSnapshot.path;
                osInfoPath = snapshotPath + '/os_info';

                log.info(' # - Load os_info from ' + snapshotPath);
                webDist.loadOsInfo(osInfoPath, function (err, results) {
                    cb(err, results);
                });
            } else {
                snapshotPath = path.join(distPath, targetSnapshot.path);
                osInfoPath = path.join(snapshotPath, 'os_info');

                log.info(' # - Load os_info from ' + snapshotPath);
                fsDist.loadOsInfo(osInfoPath, function (err, results) {
                    cb(err, results);
                });
            }
        },
        function (osInfo, cb) {
            async.eachLimit(osInfo, 1, function (targetOS, cb1) {
                var hostOS = util.getTargetOS(os.platform(), os.arch()).os;

                if (targetOS !== hostOS) {
                    var msg = 'Skip generating installer for ' + targetOS + '... hostOS(' + hostOS + ')';
                    log.warn(' # ' + msg);
                    cb1(null);
                } else {
                    log.info(' # - Generating an installer for ' + targetOS);

                    var opts = {
                        log: log,
                        metaPkgList: metaPkgList,
                        excludePkgList: excludePkgList,
                        installerTitle: installerTitle,
                        outputName: outputName
                    };
                    installer.generateInstaller(distName, distPath, baseRepoUrl, targetSnapshot, targetOS, opts, monitor, cb1);
                }
            },
            function (err) {
                cb(err);
            });
        }
    ],
    function (err) {
        callback(err);
    });
}


function createImage(distribution, options, callback) {

    if (!distribution) {
        return callback(new Error('distribution object is not given'));
    }

    var distName = distribution.name;
    var distPath = distribution.path;
    var targetSnapshot = null;

    var log = null;
    if (options && options.log) {
        log = options.log;
    } else {
        log = console;
    }

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

    var excludePkgList = null;
    if (options && options.excludePkgList) {
        if (_.isArray(options.excludePkgList)) {
            excludePkgList = options.excludePkgList;
        } else {
            excludePkgList = options.excludePkgList.split(',');
        }
    }

    var baseRepoUrl = distPath;
    if (options && options.baseRepoUrl) {
        baseRepoUrl = options.baseRepoUrl;
    }

    var osList = null;
    if (options && options.targetOS) {
        osList = options.targetOS.split(',');
    }

    var skipIntegrityCheck = false;
    if (options && options.skipIntegrityCheck) {
        skipIntegrityCheck = true;
    }

    var outputName = null;
    if (options && options.outputName) {
        outputName = options.outputName;
    }

    var snapshotName = null;
    if (options && options.baseSnapshot) {
        snapshotName = options.baseSnapshot;
    }

    async.waterfall([
        function (cb) {
            // get latest snapshot
            log.info(' # - Get a snapshot ');
            distribution.searchSnapshots({ distPath: distPath, name: snapshotName }, function (err, snapshots) {
                if (!err) {
                    if (snapshots.length === 0) {
                        err = new Error('# - Any snapshot does not exist in \'' + distName + '\'');
                    } else {
                        targetSnapshot = snapshots[0];
                        log.info(' # - Target Snapshot ' + targetSnapshot.name);
                    }
                } else {
                    log.error(err);
                }
                cb(err);
            });
        },
        function (cb) {
            if (osList) {
                cb(null, osList);
            } else {
                var snapshotPath = null;
                var osInfoPath = null;

                if (utils.isURL(distPath)) {
                    snapshotPath = distPath + '/' + targetSnapshot.path;
                    osInfoPath = snapshotPath + '/os_info';

                    log.info(' # - Load os_info from ' + snapshotPath);
                    webDist.loadOsInfo(osInfoPath, function (err, results) {
                        cb(err, results);
                    });
                } else {
                    // use path.join for posix and win32 path separator.
                    snapshotPath = path.join(distPath, targetSnapshot.path);
                    osInfoPath = path.join(snapshotPath, 'os_info');

                    log.info(' # - Load os_info from ' + snapshotPath);
                    fsDist.loadOsInfo(osInfoPath, function (err, results) {
                        cb(err, results);
                    });
                }
            }
        },
        function (osInfo, cb) {
            async.eachLimit(osInfo, 1, function (os, cb1) {
                log.info(' # - Generating an image for ' + os);

                var opts = {
                    log: log,
                    excludePkgList: excludePkgList,
                    userInputUID: distribution.uid,
                    skipIntegrityCheck: skipIntegrityCheck,
                    outputName: outputName
                };

                image.generateImage(distName, distPath, baseRepoUrl, targetSnapshot, os, opts, monitor, cb1);
            },
            function (err) {
                cb(err);
            });
        }
    ],
    function (err) {
        if (err) {
            log.error('Creating an Image - Failure!');
            log.error(err);
            process.exit(-1);
        }
        log.info('Creating an Image - Success');
        process.exit(0);
    });
}
