module.exports = function (app, con, config) {
  const uuid = require("uuid");
  const Eta = require("eta");
  const fs = require("fs");

  function isFutureDate(value) {
    const d_now = new Date();
    const d_inp = new Date(value);
    return d_now.getTime() <= d_inp.getTime();
  }

  app.use(function (req, res, next) {
    res.locals.valid = true;
    if (
      req.path.includes("/api/") ||
      req.path.includes("favicon") ||
      req.path.includes("/betaLogin") ||
      req.path.includes("/redirectUrl") ||
      req.path.includes("/beta/Invite") 
    ) {
      next();
    } else {
      if (config.env == "DEV") {
        console.log("[beta.middleware.js]", req.path);
      }
      if (uuid.validate(req.signedCookies.betaToken)) {
        next();
      } else {
        // res.cookie('betaToken', uuid.v4(), { signed: true })
        const data = fs.readFileSync("templates/redr.eta.html", "utf8");
        res.locals.valid = false;
        res.send(
          Eta.render(data, {
            siteTitel: "Pointsight - BetaLogin",
            redirectUrl: "/betaLogin",
          })
        );
      }
    }
  });

  app.post("/betaLogin", function (req, res) {
    const sql = "SELECT * FROM betatokens WHERE token LIKE ? LIMIT 1";

    con.query(sql, [req.body.betatoken], function (err, result) {
      if (err) {
        throw err;
      }
      if (result.length == 0) {
        // There is atleast one result
        res.status(401);
        res.setHeader("Content-Type", "application/json");
        res.send(
          JSON.stringify({ state: "Failed", message: "Invalid API key" })
        );
      } else {
        if (isFutureDate(result[0].expire)) {
          // Has the key expired?
          res.status(200);
          res.cookie("betaToken", uuid.v4(), { signed: true });
          res.redirect("/");
        } else {
          // Yes? Then no passing!
          res.status(401);
          res.setHeader("Content-Type", "application/json");
          res.send(
            JSON.stringify({ state: "Failed", message: "Expires API key" })
          );
        }
      }
    });

    console.log(req.body);
  });
  app.get("/beta/Invite", function (req, res) {
    const myInv = req.query.invite; // Invite code
    let invtee = req.query.invitee; // Used for personalized invites
    if(invtee == undefined){
      invtee = "Someone"; // Fallback if none is given
    }
    if (myInv == undefined) {
      const data = fs.readFileSync("templates/redr.eta.html", "utf8");
      res.locals.valid = false;
      res.send(
        Eta.render(data, {
          siteTitel: "Pointsight",
          redirectUrl: "/",
        })
      );
    } else {
      const data = fs.readFileSync("templates/beta/invitePage.eta.html", "utf8");
      res.send(
        Eta.render(data, {
          siteTitel: "Pointsight - BetaToken - Invite",
          invite: myInv,
          invitee: invtee
        })
      );
    }
  });
  app.get("/betaLogin", function (req, res) {
    if (req.query.betaKey != undefined) {
      console.log(req.query.betaKey);
      const sql = "SELECT * FROM betatokens WHERE token LIKE ? LIMIT 1";

      con.query(sql, [req.query.betaKey], function (err, result) {
        if (err) {
          throw err;
        }
        if (result.length == 0) {
          // There is atleast one result
          res.status(401);
          res.setHeader("Content-Type", "application/json");
          res.send(
            JSON.stringify({ state: "Failed", message: "Invalid API key" })
          );
        } else {
          if (isFutureDate(result[0].expire)) {
            // Has the key expired?
            res.status(200);
            res.cookie("betaToken", uuid.v4(), { signed: true });
            res.redirect("/");
          } else {
            // Yes? Then no passing!
            res.status(401);
            res.setHeader("Content-Type", "application/json");
            res.send(
              JSON.stringify({ state: "Failed", message: "Expires API key" })
            );
          }
        }
      });
    } else {
      const data = fs.readFileSync("templates/betaLogin.eta.html", "utf8");
      res.send(
        Eta.render(data, {
          siteTitel: "Pointsight - BetaLogin",
        })
      );
    }
  });
};
