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 DIO Api' });
    })
    .post('/getio', (req, res, n) => {
        if (!config.permission.dio) return n('ERR9000');

        res.api_res = {
            record: [],
            rt: {
                di: {},
                do: {}
            }
        };

        let pdi = new Promise((resolve, reject) => {
            let id = 1;
            let dis = {};
            ! function dichk(i) {
                if (i > 8) return resolve({ data: dis, key: 'di' });
                dis[i] = 0;
                exec(`ditchk ${i}`, (err, sout, serr) => {
                    if (err) return dichk(++i);
                    dis[i] = sout.replace(/\n/, '');
                    dichk(++i);
                });
            }(id)
        });

        let pdo = new Promise((resolve, reject) => {
            let id = 1;
            let dos = {};
            ! function dochk(i) {
                if (i > 8) return resolve({ data: dos, key: 'do' });
                dos[i] = 0;
                exec(`dotchk ${i}`, (err, sout, serr) => {
                    if (err) return dochk(++i);
                    dos[i] = sout.replace(/\n/, '');
                    dochk(++i);
                });
            }(id)
        });

        Promise.all([pdi, pdo])
            .then(r => {
                for (let i in r) {
                    if (r[i].key == 'di') {
                        res.api_res.rt.di = r[i].data;
                    } else if (r[i].key == 'do') {
                        res.api_res.rt.do = r[i].data;
                    }
                }
                return n();
            })
            .catch(e => n());
    })
    .post('/dotrun', (req, res, n) => {
        if (!config.permission.dio) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.pin) return n('ERR0001');
        if (!('value' in arr.data)) return n('ERR0002');

        exec(`dotrun ${arr.data.pin} ${arr.data.value}`, (err, sout, serr) => {
            res.api_res = {
                record: []
            };

            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 obj = so.get(req.headers['x-auth-token']);
            let u = '';
            if (obj != null && 'user' in obj && 'account' in obj.user) u = obj.user.account;

            let query = "select * from ??.?? where `douid` = ?";
            let param = [config.db.db1, 'dolist', arr.data.pin];
            res.db.query(query, param, (err, row) => {
                if (err || row.length == 0) return n();
                let q = "insert into ??.?? (`eventtag`, `iolabel`, `ioname`, `iosetting1`, `iosetting2`, `iosetting3`, `ioevent`, `ioeventtst`) values ";
                let p = [config.db.db2, 'jciocert'];
                let doStat = sout.replace(/\n/, '') == 1 ? 1 : 0;
                let str = `('WEB', 'DO${row[0].douid}', '${row[0].doname}', '${row[0].dologic}', '${doStat}', '${u}', '${doStat}', unix_timestamp())`;
                res.db.query(q + str, p, (err, row) => n());
            });
        });
    })
    .post('/getdioinfo', (req, res, n) => {
        if (!config.permission.dio) 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 q = "select * from ??.??";
		let pdi = tool.promiseQuery(res, q, [config.db.db1, 'dilist'], 'di');
		let pdo = tool.promiseQuery(res, q, [config.db.db1, 'dolist'], 'do');

		res.api_res = {
			record:[],
			rt: {
				di: [],
				do: []
			}
		};

		Promise.all([pdi,pdo])
			.then(r => {
				for(let i in r){
					if(r[i].key == 'di') res.api_res.rt.di = r[i].data;
					else if(r[i].key == 'do') res.api_res.rt.do = r[i].data;
				}
				return n();
			})
			.catch(e => n('ERR8000'));
    })
	.post('/setdioinfo', (req,res,n) => {
		if(!config.permission.dio) return n('ERR9000');
		// if(!tool.checkPermission(req)) return n('ERR9000');
		let arr = req.body;
		if(!arr.data) return n('ERR0000');
		if(!arr.data.di || typeof (arr.data.di) != 'object' || Object.keys(arr.data.di).length == 0) return n('ERR0005');
		if(!arr.data.do || typeof (arr.data.do) != 'object' || Object.keys(arr.data.do).length == 0) return n('ERR0006');

        res.api_res = {
            record: []
        }

		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 ?? = unix_timestamp() , ";
		let sub = " ?? = case ?? ";
		let dos = [];
		let dis = [];
		let di_logic = "";
		let di_name = "";
		let do_logic = "";
		let do_name = "";
		let where = " where ?? in (?)";
		for(let i=1; i<=8; i++){
			dos.push(`do${i}`);
			dis.push(`di${i}`);
			if(arr.data.do[`do${i}`] && 'logic' in arr.data.do[`do${i}`]){
				do_logic += ` when 'do${i}' then ${arr.data.do[`do${i}`].logic == 1 ? 1 : 0} `;
			}
			if(arr.data.do[`do${i}`] && 'name' in arr.data.do[`do${i}`]){
				do_name += ` when 'do${i}' then ${res.db.escape(arr.data.do[`do${i}`].name)} `;
			}
			if(arr.data.di[`di${i}`] && 'logic' in arr.data.di[`di${i}`]){
				di_logic += ` when 'di${i}' then ${arr.data.di[`di${i}`].logic == 1 ? 1 : 0} `;
			}
			if(arr.data.di[`di${i}`] && 'name' in arr.data.di[`di${i}`]){
				di_name += ` when 'di${i}' then ${res.db.escape(arr.data.di[`di${i}`].name)} `;
			}
		}
		do_logic += " end ";
		do_name += " end ";
		di_logic += " end ";
		di_name += " end ";

		let diq = `${query} ${sub} ${di_logic} , ${sub} ${di_name} ${where}`;
		let doq = `${query} ${sub} ${do_logic} , ${sub} ${do_name} ${where}`;

		let pdi = tool.promiseQuery(res, diq, [config.db.db1, 'dilist', 'di_modify_date', 'dilogic', 'diid', 'diname', 'diid', 'diid', dis]);
		let pdo = tool.promiseQuery(res, doq, [config.db.db1, 'dolist', 'do_modify_date', 'dologic', 'doid', 'doname', 'doid', 'doid', dos]);

		Promise.all([pdi, pdo])
			.then(r => n())
			.catch(e => n('ERR8002'))
	})
    .all('*', rt.send);

module.exports = router;