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

router
    .get('/', (req, res) => {
        res.send({ name: 'WebIO Schedule API' });
    })
    .post(['/getschedulelist', '/getschedule'], (req, res, n) => {
        if (!config.permission.schedule) return n('ERR9000');
        let s = false;
        let arr = req.body;
        if (req.url == '/getschedule') {
            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 ??.?? ";
        let order = " order by `ioscheduleuid` desc ";
        let param = [config.db.db1, 'ioschedulet'];
        if (s) {
            query += " where `ioschedulet` = ? ";
            param.push(arr.data.id);
        }

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

            res.api_res = {
                record: tool.checkArray(row),
                rt: {
                    'do': [],
                    'leone': [],
                    'iogroup': []
                }
            };

            let dos = [];
            let les = [];
            let ios = [];
            let regex = {
                do: /^do([0-9]+)$/,
                leone: /^leone([0-9]+)$/,
                iogroup: /^iogroup([0-9]+)$/
            }
            for (let i in row) {
                let str = row[i].ioscheduleio;
                let t = str.split(',');
                if (t.length == 0) continue;
                for (let j in t) {
                    if (regex.do.test(t[j])) {
                        dos.push(t[j].replace(regex.do, '$1'));
                    } else if (regex.leone.test(t[j])) {
                        les.push(t[j].replace(regex.leone, '$1'));
                    } else if (regex.iogroup.test(t[j])) {
                        ios.push(t[j].replace(regex.iogroup, '$1'));
                    }
                }
            }

            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 => {
                    for (let i in r) {
                        if (r[i].key == 'do') {
                            res.api_res.rt.do = r[i].data;
                        } else if (r[i].key == 'leone') {
                            res.api_res.rt.leone = r[i].data;
                        } else if (r[i].key == 'iogroup') {
                            res.api_res.rt.iogroup = r[i].data;
                        }
                    }
                    return n();
                })
                .catch(err => {
                    return n();
                })
        });
    })
    .post('/delschedule', (req, res, n) => {
        if (!config.permission.schedule) 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 `ioscheduleuid` = ? ";
        let param = [config.db.db1, 'ioschedulet', arr.data.id];

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

            res.api_res = {
                record: []
            };
            return n();
        });
    })
    .post('/swschedule', (req, res, n) => {
        if (!config.permission.schedule) 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 active = arr.data.active == 1 ? 1 : 0;

        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 `ioscheduleactive` = (case when `ioscheduleactive` = '1' then '0' else '1' end) where `ioscheduleuid` = ? ";
        let param = [config.db.db1, 'ioschedulet', arr.data.id];

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

            res.api_res = {
                record: []
            };
            return n();
        });
    })
    .post('/addschedule', (req, res, n) => {
        if (!config.permission.schedule) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.name) return n('ERR0026');
        if (!('active' in arr.data)) return n('ERR0032');
        if (!arr.data.devs) return n('ERR0029');
        if (!arr.data.action) return n('ERR0030');
        if (!('min' in arr.data) || !isFinite(arr.data.min) || !(arr.data.min >= 0 && arr.data.min < 60)) return n('ERR0033');
        if (!('hour' in arr.data) || !isFinite(arr.data.hour) || !(arr.data.hour >= 0 && arr.data.hour < 24)) return n('ERR0034');
        if (!arr.data.week) {
            if (!arr.data.day || !isFinite(arr.data.day) || !(arr.data.day > 0 && arr.data.day <= 31)) return n('ERR0035');
            if (!arr.data.month || !isFinite(arr.data.month) || !(arr.data.month > 0 && arr.data.month <= 12)) return n('ERR0036');
        }

        let tmp = arr.data.action.split(',');
        if (tmp.length != 2) 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.db1;
        res.db.connect();

        let active = arr.data.active == 1 ? 1 : 0;

        let d = '';
        let m = '';
        let w = '';
        if (arr.data.week) {
            w = arr.data.week;
            d = '-';
            m = '-';
        } else {
            w = '-';
            d = arr.data.day;
            m = arr.data.month;
        }

        let query = "insert into ??.?? (\
			`ioschedulename`, \
			`ioscheduleactive`, \
			`ioscheduleio`, \
			`ioschedulecmd`, \
			`ioscheduleparam1`, \
			`ioscheduleparam2`, \
			`ioscheduleparam3`, \
			`ioscheduleparam4`, \
			`ioscheduleparam5`, \
			`ioschedule_add_date`) values (?,?,?,?,?,?,?,?,?,unix_timestamp())";
        let param = [config.db.db1, 'ioschedulet', arr.data.name, active, arr.data.devs, arr.data.action, arr.data.min, arr.data.hour, d, m, w];

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

            res.api_res = {
                record: []
            };
            return n();
        });
    })
	.post('/editschedule', (req,res,n) => {
		if(!config.permission.schedule) 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 (!('active' in arr.data)) return n('ERR0032');
        if (!arr.data.devs) return n('ERR0029');
        if (!arr.data.action) return n('ERR0030');
        if (!('min' in arr.data) || !isFinite(arr.data.min) || !(arr.data.min >= 0 && arr.data.min < 60)) return n('ERR0033');
        if (!('hour' in arr.data) || !isFinite(arr.data.hour) || !(arr.data.hour >= 0 && arr.data.hour < 24)) return n('ERR0034');
        if (!arr.data.week) {
            if (!arr.data.day || !isFinite(arr.data.day) || !(arr.data.day > 0 && arr.data.day <= 31)) return n('ERR0035');
            if (!arr.data.month || !isFinite(arr.data.month) || !(arr.data.month > 0 && arr.data.month <= 12)) return n('ERR0036');
        }

        let tmp = arr.data.action.split(',');
        if (tmp.length != 2) 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.db1;
        res.db.connect();

        let active = arr.data.active == 1 ? 1 : 0;

        let d = '';
        let m = '';
        let w = '';
        if (arr.data.week) {
            w = arr.data.week;
            d = '-';
            m = '-';
        } else {
            w = '-';
            d = arr.data.day;
            m = arr.data.month;
        }

        let query = "update ??.?? set \
			`ioschedulename` = ? , \
			`ioscheduleactive` = ? , \
			`ioscheduleio` = ? , \
			`ioschedulecmd` = ? , \
			`ioscheduleparam1` = ? , \
			`ioscheduleparam2` = ? , \
			`ioscheduleparam3` = ? , \
			`ioscheduleparam4` = ? , \
			`ioscheduleparam5` = ? , \
			`ioschedule_add_date` = unix_timestamp() \
			where \
			`ioscheduleuid` = ?";
        let param = [config.db.db1, 'ioschedulet', arr.data.name, active, arr.data.devs, arr.data.action, arr.data.min, arr.data.hour, d, m, w, arr.data.id];

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

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

module.exports = router;