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, n) => {
        // 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();

        res.send({ name: 'WebIO IPCam API' });
    })
    .post('/getipcamlist', async (req,res,n) => {
        if(!config.permission.ipcam) return n('ERR9000');
        
        try{
            res.db = await mysql.getConn();
        }catch(e){
            return n('ERR8100');
        }

        let query = "select * from ??.??";
        let param = [config.db.db1, 'ipcam'];
        res.db.query(query, param, (err, row) => {
            if(err) return n('ERR8000');

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

            n();
        });
    })
    .post('/addipcam', (req,res,n) => {
        if(!config.permission.ipcam) return n('ERR9000');
        if(!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if(!arr.data) return n('ERR0000');
        if(!arr.data.ip) return n('ERR0010');
        if(!arr.data.name) return n('ERR0026');
        
        if(!/^\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3}$/.test(arr.data.ip)) return n('ERR0025');

        // 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();
        res.send('aaa');
    })
    .all('*', rt.send);

module.exports = router;