import cfg from "../config.mjs";
import db from "../sql.mjs";
import lib from "../lib.mjs";
import f0cklib from "../routeinc/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]) {
      const blah = {
        user_id: req.session.id,
        mode: mode,
        theme: req.theme ?? "f0ck"
      };

      await db`
        insert into "user_options" ${
          db(blah, 'user_id', 'mode', 'theme')
        }
        on conflict ("user_id") do update set
          mode = excluded.mode,
          theme = excluded.theme,
          user_id = excluded.user_id
      `;
    }
    res.redirect(`/${referer}`);
  });

  router.get(/^\/ranking$/, async (req, res) => {
    try {
      const list = await db`
      select
        "user".user,
        coalesce("user_options".avatar, 47319) as avatar,
        count(distinct(tag_id, item_id)) as count
      from "tags_assign"
      left join "user" on "user".id = "tags_assign".user_id
      left join "user_options" on "user_options".user_id = "user".id
      group by "user".user, "user_options".avatar
      order by count desc
      `;
      const stats = await lib.countf0cks();

      const hoster = await db`
        with t as (
          select
            split_part(substring(src, position('//' in src)+2), '/', 1) part
          from items
        )
        select t.part, count(t.part) as c
        from t
        group by t.part
        order by 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;
};
