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

router
    .get('/', (req, res) => {
        res.send({name: 'WebIO Leone API'});
    })
    .post('/scanleone', (req, res, n) => {
        if (!config.permission.leone) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.ip || !/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/.test(arr.data.ip)) return n('ERR0010');
        if (!arr.data.password) return n('ERR0017');

        let ips = arr.data.ip.trim().split('.');
        for (var i in ips) {
            if (ips[i] < 0 || ips[i] > 255) return n('ERR0025');
        }

        if (fs.existsSync(config.cmdpath.scanleone)) {
            fs.unlinkSync(config.cmdpath.scanleone);
        }
        if (fs.existsSync(config.cmdpath.scanleone_end)) {
            fs.unlinkSync(config.cmdpath.scanleone_end);
        }

        let cmd = `echo '${arr.data.ip} ${arr.data.password}' > ${config.cmdpath.scanleone}`;
        exec(cmd, (err, sout, serr) => {
            if (err) return n('ERR7000');

            ! function chkEnd() {
                fs.exists(config.cmdpath.scanleone_end, exists => {
                    if (exists) {
                        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 query = "select `leonename`, `leoneip`, `leonelistuid` from ??.?? where `temporary` = '1' ";
                        let param = [config.db.db1, 'leonelist'];
                        res.db.query(query, param, (err, row) => {
                            if (err) return n('ERR8000');

                            let data = {};
                            data.record = tool.checkArray(row);
                            res.api_res = data;
                            return n();
                        });
                    }else{
                        setTimeout(chkEnd, 1000);
                    }
                });
            }()
        });
    })
    .post(['/getleonelist', '/getleone'], (req, res, n) => {
        if (!config.permission.leone) return n('ERR9000');
        let s = false;
        let arr = req.body;
        if (req.url == '/getleone') {
            s = true;
            if (!arr.data) return n('ERR0000');
            if (!arr.data.id) return n('ERR0028');
        }

        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 query = "select * from ??.?? where `temporary` = '0' ";
        let param = [config.db.db1, 'leonelist'];
        if (s) {
            query += " and `leonelistuid` = ? ";
            param.push(arr.data.id);
        }
        let order = " order by `leonelistuid` desc ";
        res.db.query(query + order, param, (err, row) => {
            if (err) return n('ERR8000');

            tool.getLeoneRT(rts => {
                let data = {};
                data.record = tool.checkArray(row);
                data.rt = {};
                data.rt.status = tool.checkArray(rts);
                res.api_res = data;
                return n();
            });
        });
    })
    .post('/addleone', (req, res, n) => {
        let arr = req.body;
        if (!config.permission.leone) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        if (!arr.data) return n('ERR0000');
        if (!arr.data.name) return n('ERR0026');
        if (!arr.data.ip) return n('ERR0010');
        if (!arr.data.password) return n('ERR0017');

        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 query = "select count(*) as num from ??.?? where `temporary` = '0' ";
        let param = [config.db.db1, 'leonelist'];
        res.db.query(query, param, (err, row) => {
            if (err || row.length == 0) return n('ERR8000');
            if (row[0].num >= config.leone_limit) return n('ERR0056');

            let query = "select count(*) from ??.?? where `leoneip` = ? ";
            let p = [...param, arr.data.ip];
            res.db.query(query, p, (err, row) => {
                if (err || row.length == 0) return n('ERR8000');
                if (row[0].num > 0) return n('ERR0027');

                let query = "insert into ??.?? (`leoneip`,`leonename`,`leonepassword`,`leone_add_date`,`leone_modify_date`) values (?,?,?,unix_timestamp(),unix_timestamp())";
                let p = [...param, arr.data.ip, arr.data.name, arr.data.password];
                res.db.query(query, p, (err, row) => {
                    if (err) return n('ERR8001');

                    let data = {};
                    data.record = [];
                    res.api_res = data;
                    return n();
                });
            });
        })
    })
    .post('/delleone', (req, res, n) => {
        if (!config.permission.leone) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.id) return n('ERR0028');

        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 query = "delete from ??.?? where `leonelistuid` = ? ";
        let param = [config.db.db1, 'leonelist', arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8003');
            let data = {};
            data.record = [];
            res.api_res = data;
            return n();
        });
    })
    .post('/editleone', (req, res, n) => {
        if (!config.permission.leone) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.id) return n('ERR0028');
        if (!arr.data.name) return n("ERR0026");
        if (!arr.data.password) return n('ERR0017');

        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 query = "update ??.?? set \
			`leonename` = ?,\
			`leonepassword` = ?,\
			`leone_modify_date` = unix_timestamp() \
			where \
			`leonelistuid` = ? ";
        let param = [config.db.db1, 'leonelist', arr.data.name, arr.data.password, arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8002');

            let data = {};
            data.record = [];
            res.api_res = data;

            let query = "select * from ??.?? where `leonelistuid` = ? ";
            let param = [config.db.db1, 'leonelist', arr.data.id];
            res.db.query(query, param, (err, row) => {
                if (err) return n();
                if (row.length == 0) return n();

                let { leoneip, leonename, leonepassword } = row[0];
                let cmd = `sledn ${leonepassword} ${leoneip} "${leonename}"`;
                exec(cmd, (err, sout, serr) => {
                    return n();
                });
            });
        });
    })
    .post('/addscanleone', (req, res, n) => {
        if (!config.permission.leone) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.id || !Array.isArray(arr.data.id)) return n('ERR0028');

        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 ids = [];
        for (var i in arr.data.id) {
            let t = arr.data.id[i];
            if (typeof t == 'string' && t.length == 0) continue;
            ids.push(t);
        }

        if (ids.length == 0) {
            let data = {};
            data.record = [];
            res.api_res = data;
            return n();
        }

        let query = "select count(*) as num from ??.?? where `temporary` = '0' or `leonelistuid` in (?)";
        let param = [config.db.db1, 'leonelist', ids];
        res.db.query(query, param, (err, row) => {
            if (err || row.length == 0) return n('ERR8000');
            if (row[0].num >= config.leone_limit) return n('ERR0056');

            let query = "update ??.?? set `temporary` = '0', `leone_modify_date` = unix_timestamp() where `leonelistuid` in (?)";
            res.db.query(query, param, (err, row) => {
                if (err) return n('ERR8002');
                let data = {};
                data.record = [];
                res.api_res = data;
                return n();
            });
        });
    })
    .post('/clearscanleone', (req, res, n) => {
        if (!config.permission.leone) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');

        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 query = "delete from ??.?? where `temporary` = '1'";
        let param = [config.db.db1, 'leonelist'];
        res.db.query(query, param, (err, row) => {
            let data = {};
            data.record = [];
            res.api_res = data;
            return n();
        });
    })
    .all('*', rt.send);

module.exports = router;