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_pool');
const tool = require('../../includes/apiTool');
const exec = require('child_process').exec;
const so = require('../../includes/storeObject');
const crypt = require('../../libs/crypto');

router
    .get('/', (req, res) => {
        res.send({ name: 'WebIO Wristband API' });
    })
    .get('/pushdata', async(req, res, n) => {
        try {
            res.db = await mysql.getConn();
        } catch (e) {
            console.log(`Get DB Connection ERROR ${e}`);
            return n('ERR8100');
        }

        let arr = req.query;
        if (!arr.mac) return n('ERR0000');
        if (!arr.devid) return n('ERR0000');
        let query = "insert into ??.?? values (null, ?, ?,?,?,?,?,?,?,?,?,?,?,?,unix_timestamp())";
        let param = [
            config.db.db9,
            'rawdata',
            arr.devid || '',
            arr.mac || '',
            arr.val2 || '',
            arr.val3 || '',
            arr.val4 || '',
            arr.val5 || '',
            arr.val6 || '',
            arr.val7 || '',
            arr.val8 || '',
            arr.val9 || '',
            arr.val10 || '',
            arr.val11 || '',
            arr.timestamp || '',
        ];
        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8001');
            res.api_res = {
                record: []
            };
            let q = "select count(*) as c from ??.?? where `mac` = ?";
            let p = [config.db.db9, 'wristband', arr.mac];
            res.db.query(q, p, (err, row) => {
                    let pros = [];
                    if (!(err || row.length == 0 || row[0].c > 0)) {
                        let q = "insert into ??.?? (`mac`, `name`, `cuser`, `muser`, `ctime`, `mtime`) values (?, '', 'API', 'API', unix_timestamp(), unix_timestamp())";
                        let p = [config.db.db9, 'wristband', arr.mac];
                        pros.push(tool.promiseQuery(res, q, p, 'q1'));
                    }

                    let lq = "insert into ??.?? (`mac`, `devid`, `val2`, `val3`, `val4`, `val5`, `val6`, `val7`, `val8`, `val9`, `val10`, `val11`, `timestamp`, `ctime`, `mtime`) values \
                    (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, unix_timestamp(), unix_timestamp()) ON DUPLICATE KEY \
                    update \
                        `devid` = ?, \
                        `val2` = ?, \
                        `val3` = ?, \
                        `val4` = ?, \
                        `val5` = ?, \
                        `val6` = ?, \
                        `val7` = ?, \
                        `val8` = ?, \
                        `val9` = ?, \
                        `val10` = ?, \
                        `val11` = ?, \
                        `timestamp` = ?, \
                        `mtime` = unix_timestamp()";
                    let lp = [config.db.db9, 'lastdata',
                        arr.mac,
                        arr.devid,
                        arr.val2 || '',
                        arr.val3 || '',
                        arr.val4 || '',
                        arr.val5 || '',
                        arr.val6 || '',
                        arr.val7 || '',
                        arr.val8 || '',
                        arr.val9 || '',
                        arr.val10 || '',
                        arr.val11 || '',
                        arr.timestamp || '',
                        arr.devid,
                        arr.val2 || '',
                        arr.val3 || '',
                        arr.val4 || '',
                        arr.val5 || '',
                        arr.val6 || '',
                        arr.val7 || '',
                        arr.val8 || '',
                        arr.val9 || '',
                        arr.val10 || '',
                        arr.val11 || '',
                        arr.timestamp || ''
                    ]

                    pros.push(tool.promiseQuery(res, lq, lp, 'q2'));

                    Promise.all(pros)
                        .then(r => {
                            n()
                        })
                        .catch(err => {
                            console.log(err);
                            n();
                        })

                })
                // n();
        })
    })
    .post('*', async(req, res, n) => {
        try {
            res.db = await mysql.getConn();
        } catch (e) {
            console.log(`Get DB Connection ERROR ${e}`);
            return n('ERR8100');
        }
        n();
    })
    .post('/getstatus', (req, res, n) => {
        if (!config.permission.wristband) return n('ERR9000');

        let query = "select w.`name`, w.`mac` as wristband, \
            coalesce(l.`name`, l2.`name`) as locname, \
            coalesce(case when tmp2.`wlocrtloc` = 'NG' then null else tmp2.`wlocrtloc` end, ll.`devid`) as locid, \
            ll.*\
            from ??.?? w\
            left join ??.?? tmp2 \
            on tmp2.`wlocrtmac` = w.`mac` \
            left join ??.?? ll \
            on ll.`mac` = w.`mac` \
            left join ??.?? l \
            on \
            l.`serialnumber` = tmp2.`wlocrtloc` \
            and tmp2.`wlocrtloc` != 'NG' \
            left join ??.?? l2\
            on \
            l2.`serialnumber` = ll.`devid` \
            where \
            w.`switch` = 1 ";
        let param = [config.db.db9, 'wristband', config.db.db9, 'wlocationrt', config.db.db9, 'lastdata', config.db.db9, 'location', config.db.db9, 'location', ];

        let sortfield = '';
        let sortorder = '';

        if (req.body.data && req.body.data.sort) {
            if (req.body.data.sort.field) sortfield = req.body.data.sort.field;
            if (req.body.data.sort.order) sortorder = req.body.data.sort.order;
        }

        switch (sortfield) {
            case 'mac':
            case 'val2':
            case 'val3':
            case 'val4':
            case 'val5':
            case 'val6':
            case 'val7':
            case 'val8':
            case 'val9':
            case 'val10':
            case 'val11':
                query += `order by ll.${sortfield} ${sortorder}`;
                break;
            case 'loc':
                query += `order by locname ${sortorder}`;
                break;
            case 'time':
                query += 'order by ll.`timestamp` ' + sortorder;
                break;
            case 'name':
                query += `order by w.name ${sortorder}`;
            default:
                query += 'order by w.`uid`';
                break;
        }

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

            res.api_res = {
                record: tool.checkArray(row)
            }
            n();
        })
    })
    .post('/getwristbandlist', (req, res, n) => {
        if (!config.permission.wristband) return n('ERR9000');

        let query = "select * from ??.?? ";
        let param = [config.db.db9, 'wristband'];

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

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

            n();
        })
    })
    .post('/delwristband', (req, res, n) => {
        if (!config.permission.wristband) 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.query(`use ${config.db.db9}`);
        let query = "delete from ??.?? where `uid` = ?";
        let param = [config.db.db9, 'wristband', arr.data.id];

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

            res.api_res = {
                record: []
            };
            n();
        });
    })
    .post('/addwristband', (req, res, n) => {
        if (!config.permission.wristband) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000')
        if (!arr.data.mac) return n('ERR0060');

        let query = "select count(*) as c from ??.?? where `mac` = ?";
        let param = [config.db.db9, 'wristband', arr.data.mac];

        res.db.query(query, param, (err, row) => {
            if (err || row.length == 0) return rt.err(res, err, n, "ERR8000");
            if (row[0].c > 0) return n("ERR0061");

            let name = arr.data.name || '';
            let identity = arr.data.identity || 0;
            let monitor = arr.data.monitor || 0;
            let notify = arr.data.notify || 0;
            let sw = arr.data.switch || 0;

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

            let query = "insert into ??.?? (`mac`, `name`, `identity`, `monitor`, `notify`, `switch`, `cuser`, `muser`, `ctime`, `mtime`) values \
                ( ?, ?, ?, ?, ?, ?, ?, ?, unix_timestamp(), unix_timestamp() )";
            let param = [config.db.db9, 'wristband', arr.data.mac, name, identity, monitor, notify, sw, u, u];

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

                res.api_res = {
                    record: []
                };
                n();
            });
        })
    })
    .post('/editwristband', (req, res, n) => {
        if (!config.permission.wristband) 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');

        let name = arr.data.name || '';
        let identity = arr.data.identity || 0;
        let monitor = arr.data.monitor || 0;
        let notify = arr.data.notify || 0;
        let sw = arr.data.switch || 0;

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

        let query = "update ??.?? set \
            `name` = ?, \
            `identity` = ?, \
            `monitor` = ?, \
            `notify` = ?, \
            `switch` = ?, \
            `muser` = ?, \
            `mtime` = unix_timestamp() \
            where \
            `uid` = ?";
        let param = [config.db.db9, 'wristband', name, identity, monitor, notify, sw, u, arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return rt.err(res, err, n, 'ERR8002');

            res.api_res = {
                record: []
            }
            n();
        })
    })
    .post('/getwristbandlocpath', (req, res, n) => {
        if (!config.permission.wristband) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.mac) return n('ERR0060');
        if (!arr.data.stime || !arr.data.etime) return n('ERR0015');

        let pros = [];
        let query = "select log.*, dev.`name` as devname \
            from ??.?? log \
            left join ??.?? dev \
            on dev.`serialnumber` = log.`wloclogloc` \
            where \
            log.`wloclogmac` = ? \
            and log.`wloclogtst` >= ? \
            and log.`wloclogtst` <= ? \
            order by log.`wloclogtst` desc";
        let param = [config.db.db9, 'wlocationlog', config.db.db9, 'location', arr.data.mac, arr.data.stime, arr.data.etime];
        pros.push(tool.promiseQuery(res, query, param, 'record'));

        let rtq = "select * from ??.?? where `mac` = ?";
        let rtp = [config.db.db9, 'wristband', arr.data.mac];
        pros.push(tool.promiseQuery(res, rtq, rtp, 'rt'));

        res.api_res = {
            record: [],
            rt: {
                wristband: []
            }
        }

        Promise.all(pros)
            .then(d => {
                for (let i in d) {
                    let tmp = d[i];
                    if (tmp.key == 'rt') {
                        res.api_res.rt.wristband = tool.checkArray(tmp.data);
                    }
                    if (tmp.key == 'record') {
                        res.api_res.record = tool.checkArray(tmp.data);
                    }
                }
                return n();
            })
            .catch(err => rt.err(res, err, n, 'ERR8000'));

    })
    .post('/getlocationlist', (req, res, n) => {
        if (!config.permission.wristband) return n('ERR9000');

        let query = "select * from ??.??";
        let param = [config.db.db9, 'location'];

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

            res.api_res = {
                record: tool.checkArray(row)
            }
            n();
        });
    })
    .post('/addlocation', (req, res, n) => {
        if (!config.permission.wristband) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.sn) return n("ERR0062");
        if (!arr.data.name) return n('ERR0026');

        let query = "select count(*) as c from ??.?? where `serialnumber` = ?";
        let param = [config.db.db9, 'location', arr.data.sn];

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

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

            let query = "insert into ??.?? (`name`, `serialnumber`, `cuser`, `ctime`, `muser`, `mtime`) values (?, ?, ?, unix_timestamp(), ?, unix_timestamp())";
            let param = [config.db.db9, 'location', arr.data.name, arr.data.sn, u, u];
            res.db.query(query, param, (err, row) => {
                if (err) return rt.err(res, err, n, 'ERR8001');
                res.api_res = {
                    record: []
                }
                n();
            });
        })
    })
    .post('/editlocation', (req, res, n) => {
        if (!config.permission.wristband) 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');

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

        let query = "update ??.?? set \
            `name` = ?, \
            `muser` = ?, \
            `mtime` = unix_timestamp() \
            where \
            `uid` = ? ";
        let param = [config.db.db9, 'location', arr.data.name, u, arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return rt.err(res, err, n, 'ERR8002');

            res.api_res = {
                record: []
            };
            n();
        })
    })
    .post('/dellocation', (req, res, n) => {
        if (!config.permission.wristband) 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.query(`use ${config.db.db9}`);

        let query = "delete from ??.?? where `uid` = ?";
        let param = [config.db.db9, 'location', arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return rt.err(res, err, n, 'ERR8003');
            res.api_res = {
                record: []
            }
            n();
        })
    })
    .all('*', rt.send);

module.exports = router;