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 Log API' })
    })
    .post('/getlog', (req, res, n) => {
        if(!config.permission.log) return n('ERR9000');
        let arr = req.body;
        let p = arr.data && arr.data.p && isFinite(arr.data.p) && arr.data.p > 0 ? arr.data.p : 1;
        let per = arr.data && arr.data.perpage && isFinite(arr.data.perpage) && arr.data.perpage > 0 ? arr.data.perpage : config.perpage;

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

        let query = "select count(*) as num from ??.??";
        let param = [config.db.db2, 'jciocert'];
        res.db.query(query, param, (err, row) => {
            if(err || row.length == 0) return n('ERR0023');
            let page = res.db.recordPage(row[0].num, p, per);

            let query = "select * from ??.?? order by `ioeventtst` desc ";
            let limit = ` limit ${page.rec_start} , ${per} `;
            res.db.query(query + limit, param, (err, row) => {
                if(err) return n('ERR8000');
                let data = {};
                data.page = page;
                data.record = tool.checkArray(row);
                res.api_res = data;
                return n();
            });
        })
    })
    .all('*', rt.send);

module.exports = router;