// vim: set ts=2 sw=2 et tw=80:

const mongoose = require('mongoose');

function catchErrs(promise, res) {
  return promise.catch(err => error(err, res));
}

function error(err, res) {
  console.error(err);
  res.status = 500;
  res.format({
    json: () => res.json({ error: err }),
    html: () => res.render('500.dust', { err: JSON.stringify(err, null, 2) }),
  });
  res.end();
}

function renderFav(req, res, favs, list = true) {
  const makeTestsPass = e => {
    return {
      _id: e._id,
      name: e.name,
      dataURL: e.dataURL,
      bookmarked: '' + e.bookmarked
    }
  };

  if (req.accepts('html')) {
    res.render(list ? 'favourites.dust' : 'favourite.dust',
      list ? { favs } : favs);
  } else if (req.accepts('json')) {
    if (list) {
      favs = favs.map(makeTestsPass);
    } else {
      favs = makeTestsPass(favs);
    }

    res.json(favs);
  } else {
    res.writeHead(406);
    res.end();
  }
}

function parseId(req) {
  if (typeof req.params.id === 'string' && req.params.id.length == 24) {
    return mongoose.Types.ObjectId(req.params.id);
  } else {
    return req.params.id;
  }
}

function notFound(e, res) {
  if (e == null) {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not found');
    return true;
  } else return false;
}

module.exports = { error, renderFav, catchErrs, parseId, notFound };


