const { send } = require('micro');
const { router, get } = require('microrouter');
const { exportLetterboxd } = require('./export');
const extract = require('./extract');

/**
 * Act as a decorator to add headers a request handler
 * @param {*} handler - a request handler
 */
const setJsonHeaders = handler => (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  return handler(req, res);
};

const setCsvHeaders = handler => (req, res) => {
  let csvName = '';

  if (req.params.exportWebsite === 'letterboxd') {
    if (req.params.filter === 'done') {
      csvName = 'letterboxd-watched_films-export';
    } else if (req.params.filter === 'wish') {
      csvName = 'letterboxd-watchlist-export';
    }
  }

  res.setHeader('Content-disposition', `attachment; filename=${csvName}.csv`);
  res.setHeader('Content-Type', 'text/csv');
  return handler(req, res);
};

const prettify = object => JSON.stringify(object, null, '  ');

const about = {
  name: 'Shelob',
  description: "Extract your data (or someone else's) from senscritique.com",
  usage: 'GET /:username/:category/:filter',
  docs: 'https://github.com/mlcdf/shelob#shelob',
  src: 'https://github.com/mlcdf/shelob',
  author: {
    name: 'Maxime Le Conte des Floris',
    email: 'hello@mlcdf.com',
    url: 'https://mlcdf.com'
  }
};

// GET /
const index = (req, res) => send(res, 200, prettify(about));

const api = async (res, username, category, filter, exportWebsite, pretty) => {
  if (!['films', 'series', 'bd', 'livres', 'albums', 'morceaux'].includes(category)) {
    send(res, 400, { message: 'Invalid category parameter', documentation: 'https://github.com/mlcdf/shelob#usage' })
  }

  if (!['done', 'wish'].includes(filter)) {
    send(res, 400, { message: 'Invalid filter parameter', documentation: 'https://github.com/mlcdf/shelob#usage' })
  }

  await extract(username, category, filter)
    .then(data => {
      if (exportWebsite === 'letterboxd') {
        data = exportLetterboxd(data, filter);
        send(res, 200, data);
      } else {
        send(res, 200, pretty === 'false' ? data : prettify(data));
      }
    })
    .catch(err => {
      console.log(err);
      const code = err.statusCode ? err.statusCode : 500;
      const message = err.message ? err.message : 'Something happened';
      send(res, code, prettify({ message }));
    });
};

// GET /:username/:category/:filter/:exportWebsite?:pretty
const request = (req, res) =>
  api(
    res,
    req.params.username,
    req.params.category,
    req.params.filter,
    req.params.exportWebsite,
    req.params.pretty
  );

// GET /*
const notFound = (req, res) =>
  send(res, 404, prettify({ message: 'Not found' }));

module.exports = router(
  get('/', setJsonHeaders(index)),
  get('/:username/:category/:filter', setJsonHeaders(request)),
  get('/:username/:category/:filter/:exportWebsite', setCsvHeaders(request)),
  get('/*', setJsonHeaders(notFound))
);

@@ -950,71 +950,8 @@
 %7D;%0A%0A
-const prettify = object =%3E JSON.stringify(object, null, '  ');%0A
 %0Acon
@@ -1371,24 +1371,14 @@
 00, 
-prettify(
 about)
-)
 ;%0A%0Ac
@@ -1441,24 +1441,16 @@
 tWebsite
-, pretty
 ) =%3E %7B%0A 
@@ -2050,50 +2050,12 @@
 00, 
-pretty === 'false' ? data : prettify(data)
+data
 );%0A 
@@ -2264,25 +2264,16 @@
 , code, 
-prettify(
 %7B messag
@@ -2276,17 +2276,16 @@
 ssage %7D)
-)
 ;%0A    %7D)
@@ -2345,15 +2345,8 @@
 ite?
-:pretty
 %0Acon
@@ -2493,31 +2493,8 @@
 site
-,%0A    req.params.pretty
 %0A  )
@@ -2536,18 +2536,16 @@
  res) =%3E
-%0A 
  send(re
@@ -2556,17 +2556,8 @@
 04, 
-prettify(
 %7B me
@@ -2577,17 +2577,16 @@
 ound' %7D)
-)
 ;%0A%0Amodul

remove the ?pretty param since micro pretty print the output by default