import cfg from "../../inc/config.mjs";
import lib from "../lib.mjs";
import f0cklib from "../routeinc/f0cklib.mjs";

export default (router, tpl) => {
  router.get(/^\/random$/, lib.loggedin, async (req, res) => {
    let referer = req.headers.referer ?? '';
    let opts = {};

    if(referer.match(new RegExp(cfg.main.url.regex))) { // parse referer
      referer = referer.split(cfg.main.url.domain)[1];
      const tmp = referer.match(/^\/?(?:\/tag\/(?<tag>.+?))?(?:\/user\/(?<user>.+?)\/(?<mode>f0cks|favs))?(?:\/(?<mime>image|audio|video))?(?:\/p\/(?<page>\d+))?(?:\/(?<itemid>\d+))?$/);
      if(tmp)
        opts = tmp.groups;
    }

    const data = await f0cklib.getRandom({
      user: opts.user,
      tag: opts.tag,
      mime: opts.mime,
      page: opts.page,
      fav: opts.mode == 'favs',
      mode: req.session.mode,
      session: !!req.session
    });

    if(!data.success) {
      return res.reply({
        code: 404,
        body: tpl.render('error', {
          message: data.message,
          tmp: null
        }, req)
      });
    }

    res.redirect(encodeURI(`${data.link.main}${data.link.path}${data.itemid}`));
  });
  return router;
};
