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

var DError = require('../../../core/exception.js');
var Utils = require('../../../lib/utils.js');
var FsRepo = require('./fs-repo-api.js');

var DIST_INFO_FILE = 'distribution.info';

module.exports.loadDistributions = loadDistributions;

function loadDistributions(repoURL, distName, callback) {

    loadDistributionInfo(repoURL, function (err, dists) {
        if (err) {
            return callback(new DError('WEBREPO001', { repo: repoURL }));
        } else {
            if (dists.length === 0) {
                return callback(new DError('WEBREPO002', { repo: repoURL }));
            } else {
                var distributions;
                if (distName) {
                    distributions = _.filter(dists, function (dist) {
                        return dist.name === distName;
                    });
                } else {
                    distributions = dists;
                }
                return callback(null, distributions);
            }
        }
    });
}

// private functions
function loadDistributionInfo(repoURL, callback) {
    Utils.getTextFromUrl(repoURL + '/' + DIST_INFO_FILE, function (err, distString) {
        if (err) {
            return callback(new DError('WEBREPO003', {
                url: repoURL
            }), null);
        } else {
            return callback(err, FsRepo.loadDistributionInfoFromString(distString, repoURL));
        }
    });
}
