const express = require('express');
const router = express.Router();
const rt = require('../ResTool');
const config = require('../../config.json');
const mysql = require('../../libs/mysql_cls');
const tool = require('../../includes/apiTool');
const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const so = require('../../includes/storeObject');

router
    .get('/', (req, res) => {
        res.send({ name: 'WebIO IOCmd API' });
    })
    .post('/iocmd', (req, res, n) => {
        if (!config.permission.iocmd) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.cmd) return n('ERR0030');
        if (!arr.data.devs) return n('ERR0029');

        let cmds = arr.data.cmd.split(' ');
        if (cmds.length != 2) return n('ERR0030');
        if (cmds[0] == 2 && !(cmds[1] > 16 && cmds[1] < 30)) return n('ERR0031');

        let cmd = `echo '${cmds[0]} ${cmds[1]} ${arr.data.devs}' > ${config.cmdpath.iocmd}`;
        exec(cmd, (err, sout, serr) => {
            let data = {};
            data.record = [];
            res.api_res = data;


            res.db = new mysql();
            res.db.user = config.db.user;
            res.db.password = config.db.pass;
            res.db.host = config.db.host;
            res.db.port = config.db.port;
            res.db.database = config.db.db1;
            res.db.connect();

            let dos = [];
            let les = [];
            let ios = [];
            let devs = arr.data.devs.split(',');
            let regex_do = /^do([0-9]+)$/;
            let regex_le = /^le([0-9]+)$/;
            let regex_io = /^iogroup([0-9]+)$/;
            for (let i in devs) {
                let s = devs[i];
                if (!s.trim()) continue;
                if (regex_do.test(s)) {
                    dos.push(s.replace(regex_do, '$1'));
                } else if (regex_le.test(s)) {
                    les.push(s.replace(regex_le, '$1'));
                } else if (regex_io.test(s)) {
                    ios.push(s.replace(regex_io, '$1'));
                }
            }

            let obj = so.get(req.headers['x-auth-token']);
            let u = '';
            if (obj != null && 'user' in obj && 'account' in obj.user) u = obj.user.account;
            let pros = [];

            if (dos.length > 0) {
                let query = "select * from ??.?? where `douid` in (?)";
                let param = [config.db.db1, 'dolist', dos];
                pros.push(tool.promiseQuery(res, query, param, 'do'));
            }
            if (les.length > 0) {
                let query = "select * from ??.?? where `leonelistuid` in (?)";
                let param = [config.db.db1, 'leonelist', les];
                pros.push(tool.promiseQuery(res, query, param, 'leone'));
            }
            if (ios.length > 0) {
                let query = "select * from ??.?? where `iogroupuid` in (?)";
                let param = [config.db.db1, 'iogroup', ios];
                pros.push(tool.promiseQuery(res, query, param, 'iogroup'));
            }

            Promise.all(pros)
                .then(r => {
                    let c = r.length;
                    let q = "insert into ??.?? (`eventtag`, `iolabel`, `ioname`, `iosetting1`, `iosetting2`, `iosetting3`, `ioevent`, `ioeventtst`) values ";
                    let p = [config.db.db2, 'jciocert'];
                    // for (let i in r) {
                    ! function runLog(json) {
                        if (!json) return;
                        if (json.key == 'do') {
                            let d = json.data;
                            let qs = [];
                            for (let j in d) {
                                let doStat = execSync(`dotchk ${d[j].douid}`) == 1 ? 'HIGH' : 'LOW';
                                let str = `('WEB', 'DO${d[j].douid}', '${d[j].doname}', '${d[j].dologic}', '${doStat}', '${u}', '${doStat}', unix_timestamp())`;
                                qs.push(str);
                            }
                            tool.promiseQuery(res, q + qs.join(','), p)
                                .then(r => {
                                    c--;
                                })
                                .catch(err => {
                                    c--;
                                });
                            runLog(r.pop());
                        } else if (json.key == 'leone') {
                            let d = json.data;
                            let qs = [];
                            let mm = tool.getMode(req);
                            let act = tool.getCmd(req);
                            tool.getLeoneRT((rts) => {
                                for (let j in d) {
                                    let st = '';
                                    for (var k in rts) {
                                        if (rts[k].ip == d[j].leoneip) {
                                            for (let o in mm) {
                                                if (rts[k].mode == mm[o].mode) {
                                                    st = mm[o].name;
                                                    break;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    let cn = '';
                                    for (let k in act) {
                                        if (act[k].cmd == `${cmds[0]} ${cmds[1]}`) {
                                            cn = act[k].name;
                                            break;
                                        } else if (act[k].cmd == cmds[0]) {
                                            cn = act[k].name;
                                            break;
                                        }
                                    }
                                    let str = `('WEB', 'LeOne', '${d[j].leonename}', '-', '${st}', '${u}', '${cn}', unix_timestamp())`;
                                    qs.push(str);
                                }
                                tool.promiseQuery(res, q + qs.join(','), p)
                                    .then(r => {
                                        c--;
                                    })
                                    .catch(err => {
                                        c--;
                                    });
                                runLog(r.pop());
                            });
                        } else if (json.key == 'iogroup') {
                            let d = json.data;
                            let qs = [];
                            let act = tool.getCmd(req);
                            for (let j in d) {
                                let cn = '';
                                for (let k in act) {
                                    if (act[k].cmd == `${cmds[0]} ${cmds[1]}`) {
                                        cn = act[k].name;
                                        break;
                                    } else if (act[k].cmd == cmds[0]) {
                                        cn = act[k].name;
                                        break;
                                    }
                                }
                                let str = `('WEB', 'IOGroup', '${d[j].iogroupname}', '-', '-', '${u}', '${cn}', unix_timestamp())`;
                                qs.push(str);
                            }
                            tool.promiseQuery(res, q + qs.join(','), p)
                                .then(r => {
                                    c--;
                                })
                                .catch(err => {
                                    c--;
                                });
                            runLog(r.pop());
                        }
                    }(r.pop())

                    ! function chkFin() {
                        if (c <= 0) return n();
                        setTimeout(chkFin, 1000);
                    }()
                })
                .catch(err => {
                    return n();
                });
        });
    })
    .all('*', rt.send);

module.exports = router;