const express = require('express');
const router = express.Router();
const errMng = require('../../includes/errorManager');
const so = require('../../includes/storeObject');

router
    .get('/', (req, res) => {
        res.send({ name: 'WebIO API System' });
    })
    .all('*', (req,res,n)=>{
        if('x-auth-token' in req.headers) {
            let token = req.headers['x-auth-token'];
            if(so.chkKey(token)){
                let obj = so.get(token);
                if(obj != null) {
                    so.set(token, obj);
                }
            }
        }
        n();
    })
    .get('/showallso', (req,res)=>{
        res.send(so.show());
    })
    .use('/system', require('./system.js'))
    .use('/log', require('./log.js'))
    .use('/leone', require('./leone.js'))
    .use('/iogroup', require('./iogroup.js'))
    .use('/iocmd', require('./iocmd.js'))
    .use('/schedule', require('./schedule.js'))
    .use('/dio', require('./dio.js'))
    .use('/link', require('./link.js'))
    .use('/modbus', require('./modbus.js'));

// api error handler
router.use((err, req, res, n) => {
	if ('db' in res && typeof res.db == 'object' && 'close' in res.db && typeof res.db.close == 'function') res.db.close();

    let lngs = req.headers['accept-language'].split(',');
    let lng = null;
    if (lngs.length > 0) {
        lng = lngs[0].substring(0, 2);
    }
    res.send({
        errorCode: (typeof err != 'string' ? err.toString() : err),
        message: errMng(err, lng),
        status: 0
    });
})

module.exports = router;