import db from "../../inc/sql.mjs";
import lib from "../lib.mjs";
import config from "../config.mjs";
import fetch from "flumm-fetch";

export default (router, tpl) => {
  router.get(/^\/ranking$/, async (req, res) => {
    try {
      const list = await db`
        select
          "user".user, "user".admin,
          coalesce("user_options".avatar, ${await lib.getDefaultAvatar()}) 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, "user".admin
        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
      `;

      const favotop = await db`
        select item_id, count(*) favs
        from favorites
        group by item_id
        having count(*) > 1
        order by favs desc
        limit 10
      `;

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

  router.get(/^\/top10$/, async (req, res) => {
    const d = new Date();
    d.setMonth(d.getMonth() - 1);
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const year = d.getFullYear();

    const url = `${config.apis.stats.url1}/${year}-${month}/${config.apis.stats.url2}`;
    const options = {
      method: 'GET',
      headers: {
        Authorization: config.apis.stats.auth
      }
    };

    const topres = await (await fetch(url, options)).text();
    const list = topres.match(/(f0ck.me\/b\/)(?<link>.{8}\.\w*)/g).slice(0, 10).map(e => e.split('/')[2]);

    const f0cks = [];
    for(const l of list) {
      const f = await db`
        select id, username
        from items
        where dest = ${l}
        limit 1
      `;
      f0cks.push(f[0]);
    }

    res.reply({
      body: tpl.render('top10', {
        f0cks,
        year,
        month,
        tmp: null
      }, req)
    });
  });

  return router;
};
