/**
 * web-distribution-api.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 _ = require('underscore');

// var DError = require('../../../core/exception.js');
var fsDist = require('./fs-distribution-api.js');
var util = require('../../org.tizen.ts.base.common/util.js');
var utils = require('../../../lib/utils.js');

module.exports.loadSnapshots = loadSnapshots;
module.exports.loadPackages = loadPackages;
module.exports.loadChangeLog = loadSnapshotChageLog;
module.exports.loadOsInfo = loadOsInfo;

var SNAPSHOT_INFO_FILE = 'snapshot.info';

function loadSnapshots(repoURL, callback) {
    if (repoURL === undefined) {
        // TODO: define exception code.
        return callback(new Error(''));
    }

    var snapshotInfoURL = repoURL + '/' + SNAPSHOT_INFO_FILE;
    loadSnapshotInfo(snapshotInfoURL, callback);
}


function loadSnapshotInfo(snapshotInfoURL, callback) {

    async.waterfall([
        function (cb) {
            utils.getTextFromUrl(snapshotInfoURL, function (err, data) {
                if (err) {
                    // return cb(new DError('WEBREPO003', { url: path.dirname(snapshotInfoURL)}), []);
                    return callback(null, []);
                } else {
                    return cb(err, data);
                }
            });
        },
        function (data, cb) {
            var snapshots = fsDist.loadSnapshotInfoFromString(data);
            cb(null, snapshots);
        }
    ],
    function (err, snapshots) {
        callback(err, snapshots);
    });
}


function loadPackages(snapshotPath, callback) {
    var results = {};
    var distPath = path.dirname(path.dirname(snapshotPath));

    async.waterfall([
        function (cb) {
            loadArchivePackages(snapshotPath + '/archive_pkg_list', function (err, archives) {
                if (err) {
                    loadArchivePackages(distPath + '/archive_pkg_list', function (err1, archives) {
                        if (!err1) {
                            results.archivePackages = archives;
                        }
                        cb(err1);
                    });
                } else {
                    results.archivePackages = archives;
                    cb(null);
                }
            });
        },
        function (cb) {
            loadOsInfo(snapshotPath + '/os_info', function (err, osList) {
                if (err) {
                    var distPath = path.dirname(path.dirname(snapshotPath));;
                    loadOsInfo(distPath + '/os_info', function (err1, osList1) {
                        cb(err1, osList1);
                    });
                } else {
                    cb(null, osList);
                }
            });
        },
        function (osList, cb) {
            loadOsPackages(snapshotPath, osList, function (err, osPackages) {
                results.osPackages = osPackages;
                cb(err);
            });
        }
    ],
    function (err) {
        callback(err, results);
    });
}


function loadSnapshotChageLog(distPath, snapshotName, callback) {
    var changeLogPath = distPath + '/changes/' + snapshotName + '.log';

    utils.getTextFromUrl(changeLogPath, function (err, changelog) {
        if (err) {
            return callback(err, null);
        } else {
            return callback(err, changelog);
        }
    });
}


function loadOsPackages(snapshotPath, osList, callback) {
    var newOsPackages = {};

    async.each(osList, function (os, cb) {
        var pkgListPath = snapshotPath + '/pkg_list_' + os;
        newOsPackages[os] = {};

        async.waterfall([
            function (cb) {
                utils.getTextFromUrl(pkgListPath, cb);
            },
            function (pkgList, cb) {
                util.package.getPkgListFromString(pkgList, cb);
            },
            function (pkgList, cb) {
                _.each(pkgList, function (pkg) {
                    pkg.os = os;
                    newOsPackages[os][pkg.name] = pkg;
                });
                cb(null);
            }
        ],
        function (err) {
            cb(err);
        });
    },
    function (err) {
        callback(err, newOsPackages);
    });
}


function loadArchivePackages(archivePkgPath, callback) {
    utils.getTextFromUrl(archivePkgPath, function (err, contents) {
        if (err) {
            // return cb(new DError('WEBREPO003', { url: path.dirname(snapshotInfoURL)}), null);
            return callback(null, []);
        } else {
            var archives = contents.split('\n').filter(function (e) {
                return (e !== '');
            });
            return callback(err, archives);
        }
    });
}


function loadOsInfo(osInfoPath, callback) {
    utils.getTextFromUrl(osInfoPath, function (err, contents) {
        if (err) {
            return callback(err, []);
        } else {
            var osList = contents.split('\n').filter(function (e) {
                return (e !== '');
            });
            return callback(err, osList);
        }
    });
}
