const express = require('express');

const Ui_elementsService = require('../services/ui_elements');
const Ui_elementsDBApi = require('../db/api/ui_elements');
const wrapAsync = require('../helpers').wrapAsync;

const router = express.Router();
const { parse } = require('json2csv');

const { checkCrudPermissions } = require('../middlewares/check-permissions');

router.use(checkCrudPermissions('page_elements'));

router.post(
  '/',
  wrapAsync(async (req, res) => {
    await Ui_elementsService.create(req.body.data, req.currentUser);
    res.status(200).send(true);
  }),
);

router.post(
  '/bulk-import',
  wrapAsync(async (req, res) => {
    await Ui_elementsService.bulkImport(req, res);
    res.status(200).send(true);
  }),
);

router.put(
  '/:id',
  wrapAsync(async (req, res) => {
    await Ui_elementsService.update(req.body.data, req.body.id, req.currentUser);
    res.status(200).send(true);
  }),
);

router.delete(
  '/:id',
  wrapAsync(async (req, res) => {
    await Ui_elementsService.remove(req.params.id, req.currentUser);
    res.status(200).send(true);
  }),
);

router.post(
  '/deleteByIds',
  wrapAsync(async (req, res) => {
    await Ui_elementsService.deleteByIds(req.body.data, req.currentUser);
    res.status(200).send(true);
  }),
);

router.get(
  '/',
  wrapAsync(async (req, res) => {
    const filetype = req.query.filetype;

    const payload = await Ui_elementsDBApi.findAll(req.query, {
      currentUser: req.currentUser,
    });

    if (filetype && filetype === 'csv') {
      const fields = ['id', 'name', 'element_type', 'settings_json', 'sort_order'];
      const opts = { fields };
      try {
        const csv = parse(payload.rows, opts);
        res.status(200).attachment(csv);
        res.send(csv);
      } catch (err) {
        console.error(err);
        throw err;
      }
    } else {
      res.status(200).send(payload);
    }
  }),
);

router.get(
  '/count',
  wrapAsync(async (req, res) => {
    const payload = await Ui_elementsDBApi.findAll(req.query, { countOnly: true, currentUser: req.currentUser });
    res.status(200).send(payload);
  }),
);

router.get('/autocomplete', async (req, res) => {
  const payload = await Ui_elementsDBApi.findAllAutocomplete(req.query.query, req.query.limit, req.query.offset);
  res.status(200).send(payload);
});

router.get(
  '/:id',
  wrapAsync(async (req, res) => {
    const payload = await Ui_elementsDBApi.findBy({ id: req.params.id });
    res.status(200).send(payload);
  }),
);

router.use('/', require('../helpers').commonErrorHandler);

module.exports = router;
