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 ??.?? values (null, ?, '', 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) => {

        let query = "select w.`name`, l.`name` as locname, l2.`name` as last_locname, ll.*\
            from ??.?? w\
            left join ( \
                select * from ( \
                    select * from ??.?? \
                    where `timestamp` > unix_timestamp() - 30 order by conv(`val11`, 16, 10) desc limit 65535000\
                ) tmp group by `mac` \
            ) tmp2 \
            on tmp2.`mac` = w.`mac` \
            left join ??.?? ll \
            on ll.`mac` = w.`mac` \
            left join ??.?? l \
            on \
            l.`serialnumber` = tmp2.`devid` \
            left join ??.?? l2 \
            on \
            l2.`serialnumber` = ll.`devid` \
            ";
        let param = [config.db.db9, 'wristband', config.db.db9, 'rawdata', 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;
            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();
        })
    })
    .all('*', rt.send);

module.exports = router;