module.exports = function (app, con, apiTaxonomyCache) {
  const _ = require("underscore");
  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) {
    // API key handling middleware
    if (req.path.includes("/api/")) {
      if (req.query.key != undefined) {
        const sql = "SELECT * FROM apikeys WHERE apikey LIKE ? LIMIT 1";
        con.query(sql, [req.query.key], 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 {
           //  console.log(req.headers);
            if (
              JSON.parse(result[0].hosts).includes(req.hostname) ||
              JSON.parse(result[0].hosts).includes("*")
            ) {
              // Is the key even allowed for this host?
              if (isFutureDate(result[0].expire)) { // Has the key expired?
                next(); // Allow it to pass
                if(!_.isFinite(apiTaxonomyCache[req.query.key])){
                  apiTaxonomyCache[req.query.key] = 0;
                }
                apiTaxonomyCache[req.query.key] = apiTaxonomyCache[req.query.key]+1;
                // console.log(apiTaxonomyCache)
                /*const updateSql = "UPDATE apitaxonomy SET calls = calls+1 WHERE apikey LIKE ? AND DATE(date) = CURDATE()";
                const insertSql = "INSERT INTO apitaxonomy (apikey, calls) VALUES(?, ?);"
                con.query(updateSql, [req.query.key], function (err, result) {
                  if (err) {
                    console.error(err);
                  }
                  if(result.affectedRows == 0) {
                    con.query(insertSql, [req.query.key, 1], function (err, result) {
                      if (err) {
                        console.error(err);
                      }
                    });
                  }
                });*/
              } else {
                // Yes? Then no passing!
                res.status(401);
                res.setHeader("Content-Type", "application/json");
                res.send(
                  JSON.stringify({
                    state: "Failed",
                    message: "Expired API key",
                  })
                );
              }
            } else {
              res.status(401);
              res.setHeader("Content-Type", "application/json");
              res.send(
                JSON.stringify({
                  state: "Failed",
                  message: "Invalid Hostname for API key",
                })
              );
            }
          }
        });
      } else {
        res.status(401);
        res.setHeader("Content-Type", "application/json");
        res.send(
          JSON.stringify({ state: "Failed", message: "Missing API key" })
        );
      }
    } else {
      next();
    }
  });
};
