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');

router
    .get('/', (req, res) => {
        res.send({ name: 'WebIO Link API' });
    })
    .post('/getlinklist', (req, res, n) => {
        if (!config.permission.link) 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.db8;
        res.db.connect();

        let query = "select * from ??.?? \
			where \
			`jcioclntuid` not in ( \
				select n2.jcioclntuid \
				from ??.?? n1 \
				left join \
				??.?? n2\
				on \
				n1.`lnlcid1` = concat('ln', n2.`jcioclntuid`) \
				or n1.`lnlcid2` = concat('ln', n2.`jcioclntuid`) \
				where n2.`jcioclntuid` is not null \
			)";
        let param = [config.db.db8, 'jcioclnt', config.db.db8, 'jcioclnt', config.db.db8, 'jcioclnt'];

        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8000');

            res.api_res = {
                record: tool.checkArray(row)
            };

            return n();
        });
    })
    .post('/getlink', (req, res, n) => {
        if (!config.permission.link) 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.db8;
        res.db.connect();

        res.api_res = {
            record: [{ root: arr.data.id }],
            rt: {
                ln: [],
                lc: []
            }
        }

        let query = "select ??.??(?) as ids";
        let param = [config.db.db8, 'getLink', arr.data.id];

        res.db.query(query, param, (err, row) => {
            if (err || row.length == 0) return n('ERR8000');

            let ids = row[0].ids;
            let id = ids.split(',');
            id.splice(0, 1);

            let ida = id.filter(t => {
                if (t != '') return t;
            });

            let pros = [];

            let lnq = "select * from ??.?? where `jcioclntuid` in (?)";
            let lnp = [config.db.db8, 'jcioclnt', ida];
            pros.push(tool.promiseQuery(res, lnq, lnp, 'ln'));

            let lcq = "select c.* from ??.?? n \
				left join ??.?? c \
				on \
				c.`jcioclctuid` = substr(n.`lnlcid1`, 3) \
				or c.`jcioclctuid` = substr(n.`lnlcid2`, 3) \
				where \
				n.`jcioclntuid` in ( ? ) \
				and ( \
					substr(n.`lnlcid1`, 1,2) = 'lc' \
					or \
					substr(n.`lnlcid2`, 2,2) = 'lc' \
				) \
				and c.`jcioclctuid` is not null \
				group by c.`jcioclctuid`";
            let lcp = [config.db.db8, 'jcioclnt', config.db.db7, 'jcioclct', ida];
            pros.push(tool.promiseQuery(res, lcq, lcp, 'lc'));

            Promise.all(pros)
                .then(r => {
                    for (let i in r) {
                        if (r[i].key == 'lc') res.api_res.rt.lc = r[i].data;
                        if (r[i].key == 'ln') res.api_res.rt.ln = r[i].data;
                    }
                    return n();
                })
                .catch(err => n('ERR8000'));
        });
    })
    .post('/addlink', (req, res, n) => {
        if (!config.permission.link) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.link || Object.keys(arr.data.link).length == 0) return n('ERR0057');
        if (!('active' in arr.data)) return n('ERR0032');
        if (!arr.data.action) return n('ERR0030');

        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.db8;
        res.db.connect();

        ! function runLoop(unit, cb) {
            if (typeof unit != 'object' || Object.keys(unit).length == 0) return cb(0);
            if (unit.type == 'ln') {
                let p1 = new Promise((resolve, reject) => {
                    runLoop(unit.id1, id => {
                        resolve({ id, key: 'id1' });
                    });
                });
                let p2 = new Promise((resolve, reject) => {
                    runLoop(unit.id2, id => {
                        resolve({ id, key: 'id2' });
                    });
                });

                Promise.all([p1, p2])
                    .then(r => {
                        let id1 = 0;
                        let id2 = 0;
                        for (let i in r) {
                            if (r[i].key == 'id1') id1 = r[i].id;
                            if (r[i].key == 'id2') id2 = r[i].id;
                        }

                        let q = "insert into ??.?? \
							(`lnname`, `lnlcid1`, `lnlcid2`, `lnlcop`, `lnactive`, `lnaddtst`, `lnmodtst`) values (?,?,?,?,'1',unix_timestamp(),unix_timestamp())";
                        let p = [config.db.db8, 'jcioclnt', unit.name, id1, id2, unit.op];

                        res.db.query(q, p, (err, row) => {
                            if (err) return cb(0);
                            return cb(`ln${row.insertId}`);
                        });
                    })
                    .catch(err => {
                        return cb(0);
                    });
            } else if (unit.type == 'lc') {
                let q = "insert into ??.?? \
					(`lcname`, `lcioid`, `lciovalue`, `lcioop`, `lcactive`, `lcaddtst`, `lcmodtst`) values ('-', ?, ?, ?, '1', unix_timestamp(), unix_timestamp())";
                let p = [config.db.db7, 'jcioclct', unit.id, unit.value, unit.op];
                res.db.query(q, p, (err, row) => {
                    if (err) return cb(0);
                    return cb(`lc${row.insertId}`);
                });
            } else {
                return cb(0);
            }
        }(arr.data.link, (id) => {
            if (id == 0) return n('ERR8001');
            if (typeof id != 'string') id = id.toString();
            let query = "update ??.?? set \
				`lnactive` = ?, \
				`lnaction` = ? \
				where \
				`jcioclntuid` = ?";
            let param = [config.db.db8, 'jcioclnt', (arr.data.active == 1 ? 1 : 0), arr.data.action, id.substr(2)];

            res.db.query(query, param, (err, row) => {
                if (err) return n('ERR8002');

                res.api_res = {
                    record: []
                };
                return n();
            });
        });
    })
    .post('/swlinkactive', (req, res, n) => {
        if (!config.permission.link) 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.db8;
        res.db.connect();

        let query = "update ??.?? set \
			`lnactive` = (case when `lnactive` = 1 then 0 else 1 end), \
			`lnmodtst` = unix_timestamp() \
			where \
			`jcioclntuid` = ?";
        let param = [config.db.db8, 'jcioclnt', arr.data.id];

        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8002');

            res.api_res = {
                record: []
            };

            return n();
        });

    })
    .post('/dellink', (req, res, n) => {
        if (!config.permission.link) 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.db8;
        res.db.connect();

        let query = "select ??.??(?) as ids";
        let param = [config.db.db8, 'getLink', arr.data.id];

        res.db.query(query, param, (err, row) => {
            if (err || row.length == 0) return n('ERR8000');
            let ids = row[0].ids;
            let id = ids.split(',');
            id.splice(0, 1);

            let ida = id.filter(t => {
                if (t != '') return t;
            });

            let query = "delete c,n from ??.?? n \
				left join ??.?? c \
				on \
				( \
					c.`jcioclctuid` = substr(n.`lnlcid1`, 3) \
					or c.`jcioclctuid` = substr(n.`lnlcid2`, 3)\
				) \
				and ( \
					substr(n.`lnlcid1`, 1,2) = 'lc' \
					or substr(n.`lnlcid2` ,1,2) = 'lc'\
				) \
				where \
				n.`jcioclntuid` in (?)";
            let param = [config.db.db8, 'jcioclnt', config.db.db7, 'jcioclct', ida];
            res.db.query(query, param, (err, row) => {
                if (err) return n('ERR8003');

                res.api_res = {
                    record: []
                };
                return n();
            });
        });
    })
    .all('*', rt.send);

module.exports = router;