/**
 * plugin.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@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
**/

var dibs = require('../../../core/dibs.js');
var utils = require('../../../lib/utils.js');
var path = require('path');
var async = require('async');
var expressio = require('express.io');
var session = require('./session');
var _ = require('underscore');

var router = new expressio.Router();

module.exports.router = router;


router.get('/dplugins', function (req, res) {
    var extps = dibs.plugin.getAllExtensionPoints();
    var newExtps = {};
    var i;
    for (i = 0; i < extps.length; i++) {
        var extp = extps[i];
        newExtps[extp.id] = extp;
    }

    // get available dibs core version
    dibs.rpc.master.checkUpdates({}, function (err, coreVersion, updatedPlugins) {
        if (!err) {
            var result = {
                currentVersion: dibs.version,
                availableVersion: coreVersion,
                plugins: dibs.plugin.getAllPlugins(),
                activePlugins: dibs.plugin.getActivePlugins(),
                extensionPoints: newExtps
            };
            res.send(JSON.stringify(result));
        } else {
            dibs.log.warn(err.message);
            var result = {
                currentVersion: dibs.version,
                availableVersion: '0.0.0',
                plugins: dibs.plugin.getAllPlugins(),
                activePlugins: dibs.plugin.getActivePlugins(),
                extensionPoints: newExtps
            };
            res.send(JSON.stringify(result));
        }
    });
});


router.put('/dplugins/:pluginName', session.checkSession, function (req, res) {
    var pluginName = req.param('pluginName');
    dibs.rpc.master.downloadUpdate(pluginName, {}, function (err) {
        if (err) {
            dibs.log.error(JSON.stringify(err));
            res.status(503).send(JSON.stringify(err.message));
        } else {
            res.send();
        }
    });
});
