module.exports = function (app, jsonConfigGlobal, metaGlobals) {
  const fs = require("fs");
  const Eta = require("eta");
  const util = require('util');

  // Machine readable 404
  app.get("/api/*", function (req, res) {
    res.status(404);
    res.setHeader("Content-Type", "application/json");
    res.send(JSON.stringify({ state: "failed", message: "404-Unknown path" }));
  });

  // Users 404
  app.get("*", function (req, res) {
    res.status(404);
    const data = fs.readFileSync("templates/error/404.eta", "utf8");
    let debugData;
    debugData = {
      code: 404,
      message: "Unknown path",
      "Original url": req.originalUrl,
    };
    if (jsonConfigGlobal.env != "DEV") {
      debugData = {};
    }
    res.send(
      Eta.render(data, {
        desc: metaGlobals.desc,
        siteTitel: metaGlobals.titlePrefx + "404",
        debug: debugData,
      })
    );
  });


  app.use(function (err, req, res, next) {
    console.error(err.stack)
    const data = fs.readFileSync("templates/error/serverError.eta", "utf8");
    debugData = {trace: err.stack, avail: true}
    if (jsonConfigGlobal.env != "DEV") {
      debugData = {avail: false};
    }
    res.status(500)
    res.send(
      Eta.render(data, {
        desc: metaGlobals.desc,
        siteTitel: metaGlobals.titlePrefx + "500",
        debug: debugData,
        debugText: String(debugData.trace).replaceAll("\n", "<br>")
      })
    );
  })
  app.use(function (err, req, res, next) {
    console.error(err.stack)
    res.status(500)
    res.send("Something went very wrong.")
  })
};
