import cfg from "./inc/config.mjs";
import db from "./inc/sql.mjs";
import lib from "./inc/lib.mjs";
import cuffeo from "cuffeo";
import { promises as fs } from "fs";
import flummpress from "flummpress";

process.on('unhandledRejection', err => {
  console.error(err);
  throw err;
});

(async () => {
  const self = {
    _trigger: new Map(),
    trigger: function trigger(args) {
      this.call = args.call;
      this.help = args.help || false;
      this.level = args.level || 0;
      this.name = args.name;
      this.active = args.hasOwnProperty("active") ? args.active : true;
      this.clients = args.clients || [ "irc", "tg", "slack" ];
      this.f = args.f;
    },
    bot: await new cuffeo(cfg.clients)
  };

  console.time("loading");
  const modules = {
    events:  (await  fs.readdir("./src/inc/events")).filter(f => f.endsWith(".mjs")),
    trigger: (await fs.readdir("./src/inc/trigger")).filter(f => f.endsWith(".mjs"))
  };

  console.timeLog("loading", "directories");
  const blah = (await Promise.all(Object.entries(modules).map(async ([dir, mods]) => ({
    [dir]: (await Promise.all(mods.map(async mod => {
      const res = await Promise.race([
        (await import(`./inc/${dir}/${mod}`)).default(self),
        new Promise((_, rej) => setTimeout(() => rej(false), timeout))
      ]);
      console.timeLog("loading", `${dir}/${mod}`);
      return res;
    }))).flat(2)
  })))).reduce((a, b) => ({...a, ...b}));

  blah.events.forEach(event => {
    console.timeLog("loading", `registering event > ${event.name}`);
    self.bot.on(event.listener, event.f);
  });

  blah.trigger.forEach(trigger => {
    console.timeLog("loading", `registering trigger > ${trigger.name}`);
    self._trigger.set(trigger.name, new self.trigger(trigger));
  });

  //console.timeEnd("loading");


  // websrv
  const app = new flummpress();
  const router = app.router;
  const tpl = app.tpl;

  app.use(async (req, res) => {
    // sessionhandler
    req.session = false;
    if(req.url.pathname.match(/^\/(s|b|t|ca)\//))
      return;
    req.theme = req.cookies.theme || 'atmos';
    req.fullscreen = req.cookies.fullscreen || 0;

    if(req.cookies.session) {
      const user = await db`
        select "user".id, "user".login, "user".user, "user".admin, "user_sessions".id as sess_id, "user_options".*
        from "user_sessions"
        left join "user" on "user".id = "user_sessions".user_id
        left join "user_options" on "user_options".user_id = "user_sessions".user_id
        where "user_sessions".session = ${lib.md5(req.cookies.session)}
        limit 1
      `;
      
      if(user.length === 0) {
        return res.writeHead(307, { // delete session
          "Cache-Control": "no-cache, public",
          "Set-Cookie": "session=; Path=/;  expires=Thu, 01 Jan 1970 00:00:00 GMT",
          "Location": req.url.pathname
        }).end();
      }

      req.session = user[0];

      // log last action
      await db`
        update "user_sessions" set ${
          db({
            last_used: ~~(Date.now() / 1e3),
            last_action: req.url.pathname,
            browser: req.headers['user-agent']
          }, 'last_used', 'last_action', 'browser')
        }
        where id = ${+user[0].sess_id}
      `;

      req.session.theme = req.cookies.theme;
      req.session.fullscreen = req.cookies.fullscreen;
      
      // update userprofile
      await db`
        insert into "user_options" ${
          db({
            user_id: +user[0].id,
            mode: user[0].mode ?? 0,
            theme: req.session.theme ?? 'atmos',
            fullscreen: req.session.fullscreen || 0
          }, 'user_id', 'mode', 'theme', 'fullscreen')
        }
        on conflict ("user_id") do update set
          mode = excluded.mode,
          theme = excluded.theme,
          fullscreen = excluded.fullscreen,
          user_id = excluded.user_id
      `;
    }
  });

  tpl.views = "views";
  tpl.debug = true;
  tpl.cache = false;
  tpl.globals = {
    lul: cfg.websrv.lul,
    themes: cfg.websrv.themes,
    modes: cfg.allowedModes
  };
  router.use(tpl);

  await router.importRoutesFromPath("src/inc/routes", tpl);

  app.listen(cfg.websrv.port);

})();
