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

const auth = async (req, res, next) => {
  if(!req.session)
    return res.redirect("/login");
  return next();
};

export default (router, tpl) => {
  router.get(/^\/?(?:\/tag\/(?<tag>.+?))?(?:\/user\/(?<user>.+?)\/(?<mode>f0cks|favs))?(?:\/(?<mime>image|audio|video))?(?:\/p\/(?<page>\d+))?(?:\/(?<itemid>\d+))?$/, async (req, res) => {
    const mode = req.params.itemid ? 'item' : 'index';
    const data = await (req.params.itemid ? f0cklib.getf0ck : f0cklib.getf0cks)({
      user: req.params.user,
      tag: req.params.tag,
      mime: req.params.mime,
      page: req.params.page,
      itemid: req.params.itemid,
      fav: req.params.mode == 'favs',
      mode: req.session.mode
    });
    if(!data.success) {
      return res.reply({
        code: 404,
        body: tpl.render('error', {
          message: data.message,
          tmp: null
        }, req)
      });
    }

    return res.reply({ body: tpl.render(mode, data, req) });
  });

  router.get(/^\/(about)$/, (req, res) => {
    res.reply({
      body: tpl.render(req.url.split[0], { tmp: null }, req)
    });
  });

  router.get(/^\/mode\/(\d)/, auth, async (req, res) => {
    const mode = +req.url.split[1];
    let referertmp = req.headers.referer;
    let referer = "";
    
    if(referertmp?.match(/f0ck\.me/))
      referer = referertmp.split("/").slice(3).join("/");

    if(cfg.allowedModes[mode]) {
      await sql("user_options")
        .insert({
          user_id: req.session.id,
          mode: mode,
          theme: req.theme ?? "f0ck"
        })
        .onConflict("user_id")
        .merge();
    }
    res.redirect(`/${referer}`);
  });

  router.get(/^\/ranking$/, async (req, res) => {
    try {
      const list = await sql('tags_assign')
        .select('user.user')
        .leftJoin('user', 'user.id', 'tags_assign.user_id')
        .groupBy('user.user')
        .orderBy('count', 'desc')
        .countDistinct('tag_id', 'item_id', { as: 'count' });

      const stats = await lib.countf0cks();

      const hoster = await sql.with('t', sql.raw("select split_part(substring(src, position('//' in src)+2), '/', 1) part from items"))
        .from('t')
        .select('t.part')
        .count('t.part as c')
        .groupBy('t.part')
        .orderBy('c', 'desc')
        .limit(20);

      res.reply({
        body: tpl.render('ranking', {
          list,
          stats,
          hoster,
          tmp: null
        }, req)
      });
    } catch(err) {
      res.end(JSON.stringify(err.message));
    }
  });

  return router;
};
