/**
 * 管理端点。负责数据库，服务器状态等内容反馈。
 */
var express = require('express');
var router = express.Router();

var configFile = require('../include/commons').CONFIG_FILE;
var config = require('../resources/config/' + configFile);

var wlyyRepo = require('../repository/database/wlyy.db.js');
var imRepo = require('../repository/database/im.db.js');

var log = require('../util/log');

var APIv1 = require('../include/endpoints').APIv1;
var _ = require('underscore');

function getWlyyTables(handler) {
    wlyyRepo.execQuery({
        "sql": "SELECT table_name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ?",
        "args": [config.wlyyDbConfig.database],
        "handler": handler
    });
}

function getImTables(handler) {
    imRepo.execQuery({
        "sql": "SELECT table_name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ?",
        "args": [config.imDbConfig.database],
        "handler": handler
    });
}

function makeResponse(dbStatus, dbName, err, result) {
    if (err) {
        dbStatus.push({
            name: dbName,
            status: 'Failed',
            message: err
        });
    } else {
        var tableList = new Array();
        _.each(result, function (row) {
            tableList.push(row.table_name);
        });

        var status = {
            name: dbName,
            status: 'OK',
            tables: tableList
        };

        dbStatus.push(status);
    }
}

/**
 * 数据库检查，包括所有表，连接状态。
 */
router.get(APIv1.Management.DbStatus, function (req, res, next) {
    var dbStatus = new Array(0);

    getImTables(function (err, result) {
        makeResponse(dbStatus, config.imDbConfig.database, err, result);

        getWlyyTables(function (err, result) {
            makeResponse(dbStatus, config.wlyyDbConfig.database, err, result);

            res.json(dbStatus);
        });
    });
});

module.exports = router;
