/**
 * server.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');
var async = require('async');
var expressio = require('express.io');
var session = require('./session');

var router = new expressio.Router();
module.exports.router = router;


router.get('/servers', session.checkSession, function (req, res) {
    var envId = req.query.environmentId;
    var servers = [];

    if ( envId ) {
        servers = dibs.getServersByEnvironment(envId);
        res.send(JSON.stringify(servers));
    } else {
        servers = dibs.getAllServers();
        var data = [];
        var sid_list = [];
        var i;

        for(i=0;i<servers.length;i++) {
            var server = {};
            server.id = servers[i].id;
            server.type = servers[i].type;
            server.host = servers[i].host;
            server.port = servers[i].port;
            server.environments = servers[i].environments.map( function(env) {
                return env.id;
            });
            data.push(server);
            sid_list.push(server.id);
        }

        async.map(sid_list,function(id, cb){
            dibs.rpc.master.getServerStatus(id, function(err,d) {
                cb(err,d);
            });
        },function(err, result) {
            if(err) {
                dibs.log.error(JSON.stringify(err));
                res.status(503).send(JSON.stringify(err.message));
            }
            else {
                for(i=0;i<data.length;i++)
                {
                    data[i].status = result[i].status;
                    data[i].cpuUsage = result[i].cpuUsage;
                    data[i].memUsage = result[i].memUsage;
                    data[i].diskUsage = result[i].diskUsage;
                }
                var d = {identifier: "id", label:"id", items: data};
                res.send(JSON.stringify(d));
            }
        });
    }
});


router.get('/servers/:serverId', session.checkSession, function (req, res) {
	var serverId = req.param('serverId');
    var server = {};

    var s = dibs.getServer(serverId);
    server.id = s.id;
    server.type = s.type;
    server.host = s.host;
    server.port = s.port;

    dibs.rpc.master.getServerStatus(server.id, function(err,d) {
        if(err) {
            dibs.log.error(JSON.stringify(err));
            res.status(503).send(JSON.stringify(err.message));
        }
        else {
            server.status = d.status;
            server.cpuUsage = d.cpuUsage;
            server.memUsage = d.memUsage;
            server.diskUsage = d.diskUsage;
            res.send(JSON.stringify(server));
        }
    });
});


router.put('/servers/:serverId', session.checkSession, function (req, res) {
	var serverId = req.param('serverId');
    var operation = req.body.operation;

    async.series([
        function(cb) {
            if ( operation === "start" ) {
                dibs.rpc.master.startServer( serverId, cb );
            } else if ( operation === "stop" ) {
                dibs.rpc.master.stopServer( serverId, cb );
            } else if ( operation === "restart" ) {
                dibs.rpc.master.restartServer( serverId, cb );
            } else {
                cb( new Error("Invalid server control('"+operation+"') operation! " ) );
            }
        }
        ], function(err) {
            if (err) {
                dibs.log.error(JSON.stringify(err));
                res.status(503).send(JSON.stringify(err.message));
            } else {
                res.send();
            }
        });
});


router.get('/environments', session.checkSession, function (req, res) {
    dibs.rpc.datamgr.searchEnvironments({}, function(err, envs) {
        if(err) {
            dibs.log.error(JSON.stringify(err));
            res.status(503).send(JSON.stringify(err.message));
        }
        else {
            res.send(JSON.stringify(envs));
        }
    });
});


router.get('/dfs', session.checkSession, function (req, res) {
    var current = dibs.thisServer;

    dibs.rpc.repo.__monitorDFS({type:"MASTER_INDEX"}, function( err, idx ) {
        if(err) {
            dibs.log.error(JSON.stringify(err));
            res.status(503).send(JSON.stringify(err.message));
        }
        else {
            res.send(JSON.stringify(idx));
        }
	});
});
