import Logging from "@hibas123/nodelogging";
import config from "./config.js";

// import NLS from "@hibas123/nodeloggingserver_client";
// if (config.logging) {
//    let s = NLS(Logging, config.logging.server, config.logging.appid, config.logging.token);
//    s.send(`[${new Date().toLocaleTimeString()}] Starting application`);
// }

// if (!config.database) {
//    Logging.error("No database config set. Terminating.")
//    process.exit();
// }

if (!config.web) {
   Logging.error("No web config set. Terminating.");
   process.exit();
}

import * as i18n from "i18n";
i18n.configure({
   locales: ["en", "de"],
   directory: "./locales",
});

import Web from "./web.js";
import TestData from "./testdata.js";
import DB from "./database.js";

Logging.log("Connecting to Database");
if (config.core.dev) {
   Logging.warning("Running in dev mode! Database will be cleared!");
}
DB.connect()
   .then(async () => {
      Logging.log("Database connected", config);
      if (config.core.dev) await TestData();
      let web = new Web(config.web);
      web.listen();

      let already = new Set();
      function print(path, layer) {
         if (layer.route) {
            layer.route.stack.forEach(
               print.bind(null, path.concat(split(layer.route.path)))
            );
         } else if (layer.name === "router" && layer.handle.stack) {
            layer.handle.stack.forEach(
               print.bind(null, path.concat(split(layer.regexp)))
            );
         } else if (layer.method) {
            let me: string = layer.method.toUpperCase();
            me += " ".repeat(6 - me.length);
            let msg = `${me} /${path
               .concat(split(layer.regexp))
               .filter(Boolean)
               .join("/")}`;
            if (!already.has(msg)) {
               already.add(msg);
               Logging.log(msg);
            }
         }
      }

      function split(thing) {
         if (typeof thing === "string") {
            return thing.split("/");
         } else if (thing.fast_slash) {
            return "";
         } else {
            var match = thing
               .toString()
               .replace("\\/?", "")
               .replace("(?=\\/|$)", "$")
               .match(
                  /^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//
               );
            return match
               ? match[1].replace(/\\(.)/g, "$1").split("/")
               : "<complex:" + thing.toString() + ">";
         }
      }
      // Logging.log("--- Endpoints:    ---");
      // web.server._router.stack.forEach(print.bind(null, []))
      // Logging.log("--- Endpoints end ---")
   })
   .catch((e) => {
      Logging.error(e);
      process.exit();
   });
