const MODULE_NAME = 'SPQ.CONTROL-PANEL.ROUTER.MAIN';

const express = require('express');

const config = require('komodo-sdk/config');
const logger = require('tektrans-logger');

const redisUtil = require('../../redis-util');

const router = express.Router();
module.exports = router;

async function pageIndex(req, res) {
    const { xid } = res.locals;
    const limitedList = (await redisUtil.limitedList(xid))
        .filter((item) => item.supplier === config.handler_name);

    const limitedCount = limitedList.length;
    for (let i = 0; i < limitedCount; i += 1) {
        // eslint-disable-next-line no-await-in-loop
        const value = await redisUtil.get(limitedList[i].product);
        limitedList[i].value = value;
    }

    const products = limitedList.map((item) => item.product);
    const maxValuesArray = await redisUtil.getMaxValuesForIndicator(products, xid);
    const maxValues = {};
    const productCount = products.length;
    for (let i = 0; i < productCount; i += 1) {
        const product = products[i];
        maxValues[product] = Number(maxValuesArray[i]) || 0;
    }

    res.render(
        'main.njk',
        {
            pageTitle: 'Produk dan Limit',
            limitedList,
            maxValues,
        },
    );
}

async function pageAddProductSubmit(req, res) {
    const { xid } = res.locals;
    const { product, newLimit } = req.body;

    try {
        await redisUtil.setLimit(product, Number(newLimit) || 0);
    } catch (e) {
        logger.warn(`371F338A ${MODULE_NAME}: Exception on creating product limit`, {
            xid, product, newLimit, eCode: e.code, eMessage: e.message,
        });
    }

    res.redirect(req.baseUrl);
}

async function pageDelete(req, res) {
    const { xid } = res.locals;
    const { product } = req.params;

    try {
        await redisUtil.removeFromLimited(product, xid);
    } catch (e) {
        //
    }

    res.redirect(req.baseUrl);
}

async function pageEditProductSubmit(req, res) {
    const { product } = req.body;

    const newLimit = Math.floor(Number(req.body.newLimit));

    try {
        await redisUtil.setLimit(product, newLimit);
    } catch (e) {
        //
    }

    res.redirect(req.baseUrl);
}

async function pageAddProductQuota(req, res) {
    const { xid } = res.locals;
    const { product, raiseValue } = req.body;

    try {
        await redisUtil.incrementBy(product, raiseValue, xid);
    } catch (e) {
        //
    }

    res.redirect(req.baseUrl);
}

async function pageEditMaxValueForIndicator(req, res) {
    const { xid } = res.locals;
    const { product, maxValue } = req.body;

    try {
        logger.info(`${MODULE_NAME}: Saving max value`, {
            xid, product, maxValue,
        });

        await redisUtil.setMaxValueForIndicator(product, Number(maxValue), xid);
    } catch (e) {
        logger.warn(`${MODULE_NAME}: Exception on saving max value for indicator`, {
            xid, product, maxValue, eCode: e.code, eMessage: e.message,
        });
    }

    res.redirect(req.baseUrl);
}

router.use((req, res, next) => {
    res.locals.baseUrl = req.baseUrl;
    next();
});

router.get('/', pageIndex);
router.post('/add-product', express.urlencoded({ extended: false }), pageAddProductSubmit);

router.get('/delete/:suplier/:product', pageDelete);

router.post('/edit-product', express.urlencoded({ extended: false }), pageEditProductSubmit);
router.post('/add-quota', express.urlencoded({ extended: false }), pageAddProductQuota);

router.post('/edit-max-value-for-indicator', express.urlencoded({ extended: false }), pageEditMaxValueForIndicator);
