var express = require('express');
var cproc = require('child_process');
var bodyParser = require('body-parser');
var db_config = require('./config/db');
const mongodb = require('mongodb');
// return
var execSync = cproc.execSync;
var options = {
    inflate: true,
    limit: '100kb',
    type: 'application/octet-stream'
};
// const mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost/my_database');

var app = express();
var admin = express(); // the sub app
app.use(bodyParser.urlencoded({ extended: false }))

app.use(bodyParser.json())
var attrs = {
    configPath: "config_file",
    buildCmd: "command",
    gitPath: "git_path",
    gitGroup: "gitPathHead",
    host: "www",
    projectType: "type",
    projectAuth: "auth",
    projectDesc: "desc",
    logName: "log_name",
    jarFilePath: "target_path",
    auth: "auth",
    port: "port",
    start_command: "",
    stop_command: "",
    command2: "command2",
    node_version: "node_version"
}
var attrComs = Object.keys(attrs)
var attrComsArr = [];
for (let i of attrComs) {
    attrComsArr.push(attrs[i]);
}
// ------------UTILS------------
function parseStr2Json(str) {
    var a = {};
    var strs = str.split(" ");
    for (let i of strs) {
        if (i) {
            let os = i.split("|");
            a[os[0]] = {
                name: os[0],
                ip: os[1],
                http: os[2],
                https: os[3]
            }
        }
    }
    return a
}

function parseJson2Str(json) {
    var a = [];
    let keys = Object.keys(json);
    for (let k of keys) {
        a.push([
            json[k].name,
            json[k].ip,
            json[k].http,
            json[k].https
        ].join("|"))
    }
    return a.join(" ")
}
// ------------UTILS----------
// DB 维护数据
let db_conf = db_config.db_config();
let db_conf_keys = Object.keys(db_conf);
// 
admin.get('/get_db_config/:name/:attr', function(req, res) {
    let str = ""
    if (req.params.name == "all") {
        if (req.params.attr == "name") {
            res.send(db_conf_keys.join(" "));
        }
    } else {
        if (req.params.attr != "all") {
            res.send(db_conf[req.params.name][req.params.attr])
        } else {
            let item = db_conf[req.params.name]
            res.send(`${item.host};${item.port};${item.user};${item.pwd};${item.sys_table_list};`)
        }
    }
});
admin.get('/get_db_dump_command/:name/:opt', function(req, res) {
    if (req.params.opt != "opt") {
        res.send(db_config.get_mysql_dump_table(req.params.name));
    } else {
        res.send(db_config.get_mysql_dump_opt(req.params.name));
    }
});
admin.get('/get_db_config/refersh', function() {
    res.setHeader("Content-Type", "application/json");
    db_conf = db_config.db_config();
    db_conf_keys = Object.keys(db_conf);
    res.send({ code: "OK" })
})
// 获取节点命令


admin.get('/get_node_command/:name', function(req, res) {
    res.setHeader("Content-Type", "application/json");
    var str = execSync(`node ./get_project_config.js  -name ${req.params.name} -attr config_file/command/gitPathHead`)
    var items = String(str).replace(/\n/g, "").split("|");
    var config_file = items[0].replace(/\^/g, " ");
    var command = items[1].replace(/\^/g, " ");
    var gitGroup = items[2].replace(/\^/g, " ");
    res.send({ configPath: config_file, buildCmd: command, gitGroup: gitGroup });
});


// 获取项目配置
admin.get('/get_project_attr/:name', function(req, res) {
    res.setHeader("Content-Type", "application/json");
    var comstr = attrComsArr.join("/");
    var names = req.params.name.split("--");
    var p_name = "";
    if (names.length > 1) {
        p_name = names[0]
    } else {
        p_name = req.params.name
    }
    var str = execSync(`node ./get_project_config.js  -name ${p_name} -attr ${comstr}`)
    var items = String(str).replace(/\n/g, "").split("|");
    let rs = {},
        index = 0;
    for (let i of items) {
        rs[attrComs[index]] = i.replace(/\^/g, " ");
        index++
    }
    res.send(rs);
});


// 获取所有域名
admin.get('/get_hosts', function(req, res) {
    res.setHeader("Content-Type", "application/json");
    var str = execSync(`node ./get_project_config.js  -type hosts`)
    var items = String(str);
    res.send(items);
});

// 根据类型获取系统名称
admin.get('/get_systems_by_type', function (req, res) {
 	res.setHeader("Content-Type","application/json");
	var ui_str = execSync(`node ./get_project_config.js  -type ui -attr name`)
	ui_str = String(ui_str)
	.replace(/xyqb-ui/g,"").replace(/xjd-ui/,"xyqb-ui--xjd-ui")
	.replace(/new-paycenter-ui/g,"").replace(/paycenter-ui/,"paycenter-ui--new-paycenter-ui")
	.replace(/\s+/g,",").replace(/\n/g,"").slice(0, -1);
	var java_str = execSync(`node ./get_project_config.js  -type java -attr name`)
	var node_str = execSync(`node ./get_project_config.js  -type node -attr name`)
	var python_str = execSync(`node ./get_project_config.js  -type python -attr name`)
	var server_str = `${String(java_str)} ${String(node_str)} ${String(python_str)}`
	server_str = server_str.replace(/\s+/g,",").replace(/\n/g,"").slice(0, -1);;
	res.send({
		common:"db,redis,rabbitmq,zookeeper",
		frontend:ui_str,
		backend:server_str
	});
});

// 给jenkins使用根据类型获取系统名称
admin.get('/get_systems_by_type_for_jenkins/:_type', function(req, res) {
    let str = ""
    if (req.params._type === "frontend") {
        var ui_str = execSync(`node ./get_project_config.js  -type ui -attr name`)
        str = String(ui_str)
            .replace(/xyqb-ui/g, "").replace(/xjd-ui/, "xyqb-ui--xjd-ui")
            .replace(/new-paycenter-ui/g, "").replace(/paycenter-ui/, "paycenter-ui--new-paycenter-ui");
    } else {
        var java_str = execSync(`node ./get_project_config.js  -type java -attr name`)
        var node_str = execSync(`node ./get_project_config.js  -type node -attr name`)
        var python_str = execSync(`node ./get_project_config.js  -type python -attr name`)
        str = `${String(java_str)} ${String(node_str)} ${String(python_str)}`
    }
    str = str.replace(/\n/g, "").replace(/\s+/g, "\n");
    res.send(str);
});

// 给jenkins使用根据类型获取系统名称
admin.get('/get_systems_by_type_for_temp', function(req, res) {
    var ui_str = execSync(`node ./get_project_config.js  -type ui -attr name`)
    ui_str = String(ui_str).split(/\s+/)
    var java_str = execSync(`node ./get_project_config.js  -type java -attr name`)
    java_str = String(java_str).split(/\s+/)
    var node_str = execSync(`node ./get_project_config.js  -type node -attr name`)
    node_str = String(node_str).split(/\s+/)
    var python_str = execSync(`node ./get_project_config.js  -type python -attr name`)
    python_str = String(python_str).split(/\s+/)
    res.send({
        ui: ui_str,
        java: java_str,
        node: node_str,
        python: python_str
    });
});


// 增加一个新的nginx映射
admin.post('/add_new_proxy', function(req, res) {
    let request = req.body;
    let new_namespace = request["namespace"],
        new_ip = request["ip"],
        new_ports = request["ports"];
    var str = String(execSync(`cat ../ngrok/docker_env_name.sh`)).replace(/\n/, "");
    let data = parseStr2Json(str);
    data[new_namespace] = {
        name: new_namespace,
        ip: new_ip,
        http: new_ports.http_port,
        https: new_ports.https_port
    }

    let s = parseJson2Str(data)
    s = s.replace("\n", "")
    execSync(`echo "${s}" > ../ngrok/docker_env_name.sh`)
    cproc.exec("../ngrok/make_frp_ini_V2.sh");
    res.send({ msg: "执行完成" });
});


// 删除一个namespace映射
admin.post('/remove_proxy', function(req, res) {
    let request = req.body;
    console.log(request);
    let new_namespace = request["namespace"];
    var str = String(execSync(`cat ../ngrok/docker_env_name.sh`)).replace(/\n/, "");
    let data = parseStr2Json(str);
    delete data[new_namespace]
    let s = parseJson2Str(data)
    s = s.replace("\n", "")
    execSync(`echo "${s}" > ../ngrok/docker_env_name.sh`)
    cproc.exec("../ngrok/make_frp_ini_V2.sh");
    var last_str = String(execSync(`cat ../ngrok/docker_env_name.sh`))
    res.setHeader("Content-Type", "application/json");
    res.send({
        "details": {
            name_spaces: last_str
        },
        "success": true
    });
});

// 获取现有映射关系
admin.get('/get_proxy', function(req, res) {
    res.setHeader("Content-Type", "application/json");
    var str = execSync(`cat ../ngrok/docker_env_name.sh`)
    res.send({ namespace: String(str) });
});


// 从mongo中获取配置
admin.get('/get_project_config_from_db', function(req, res) {
    res.setHeader("Content-Type", "application/json");
    async function test() {
        let db = await mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/qaHome', async function(err, db) {
            let proconfigs = db.collection('proconfigs');
            // let blogs = await coll.find().toArray();
            let projects = await proconfigs.find().toArray();
            let re = [];
            // for (var i = 0; i < projects.length; i++) {
            // 	let project_name=projects[i]['project_name'];
            //     let temp = { project_name: projects[i] };
            //     // temp[projects[i]['project_name']] = projects[i];
            //     console.log(temp)
            //     re.push(temp);

            // }
            res.send(projects)
        });
    }
    test();

});

app.use('/config_server', admin)
console.log("http://192.168.4.3:10088/config_server/get_node_command")
app.listen(10088)