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.send({ name: 'WebIO Server IPMI/SNMP API' });
    })
    .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('/getserverlist', (req, res, n) => {
        if (!config.permission.server) return n('ERR9000');

        let query = "select * from ??.??";
        let param = [config.db.db11, 'jciocservert'];

        res.db.query(query, param, (err, row) => {
            if (err) return rt.err(res, err, n, 'ERR8000');
            res.api_res = {
                record: tool.checkArray(row)
            }
            n();
        })
    })
    .post('/addserver', (req, res, n) => {
        if (!config.permission.server) 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 (arr.data.iip) {
            if (!arr.data.iaccount) return n('ERR0016');
            if (!arr.data.ipassword) return n('ERR0017');
            if (!arr.data.imac) return n('ERR0064');
            if (!arr.data.itype) return n('ERR0009');
        }
        if (arr.data.sip) {
            if (!arr.data.smac) return n('ERR0064');
            if (!arr.data.stype) return n('ERR0009');
            if (!arr.data.sname) return n('ERR0026');
            if (!arr.data.sver) return n('ERR0065');
            if (arr.data.sver == 'v3' && !arr.data.v3level) return n('ERR0066');
            if (arr.data.v3level) {

            }
        }
    })
    .all('*', rt.send);

module.exports = router;