"use strict";

process.env.TZ = "Etc/GMT";

console.log("Loading ketr.ketran");

const express = require("express"),
  bodyParser = require("body-parser"),
  config = require("config"),
  session = require('express-session'),
  basePath = require("./lib/basepath"),
  cookieParser = require("cookie-parser"),
  app = express(),
  fs = require('fs');

const server = require("http").createServer(app);

app.use(cookieParser());

const ws = require('express-ws')(app, server);

require("./lib/console-line.js"); /* Monkey-patch console.log with line numbers */

const frontendPath = config.get("frontendPath").replace(/\/$/, "") + "/",
  serverConfig = config.get("server");

console.log("Hosting server from: " + basePath);

let userDB, chatDB;

app.use(bodyParser.json());

/* App is behind an nginx proxy which we trust, so use the remote address
 * set in the headers */
app.set("trust proxy", true);

app.set("basePath", basePath);
app.use(basePath, require("./routes/basepath.js"));

/* Handle static files first so excessive logging doesn't occur */
app.use(basePath, express.static(frontendPath, { index: false }));

const index = require("./routes/index");

if (config.has("admin")) {
  const admin = config.get("admin");
  app.set("admin", admin);
}

/* Allow loading of the app w/out being logged in */
app.use(basePath, index);

/* /chat loads the default index */
app.use(basePath + "chat", index);

/* Allow access to the 'users' API w/out being logged in */
/*
const users = require("./routes/users");
app.use(basePath + "api/v1/users", users.router);
*/

app.use(function(err, req, res, next) {
  console.error(err.message);
  res.status(err.status || 500).json({
    message: err.message,
    error: {}
  });
});

app.use(`${basePath}api/v1/chat`, require("./routes/chat"));

/* Declare the "catch all" index route last; the final route is a 404 dynamic router */
app.use(basePath, index);

/**
 * Create HTTP server and listen for new connections
 */
app.set("port", serverConfig.port);

process.on('SIGINT', () => {
  console.log("Gracefully shutting down from SIGINT (Ctrl-C) in 2 seconds");
  setTimeout(() => process.exit(-1), 2000);
  server.close(() => process.exit(1));
});

require("./db/chat").then(function(db) {
  chatDB = db;
}).then(function() {
  return require("./db/users").then(function(db) {
    userDB = db;
  });
}).then(function() {
  console.log("DB connected. Opening server.");
  server.listen(serverConfig.port, () => {
    console.log(`http/ws server listening on ${serverConfig.port}`);
  });
}).catch(function(error) {
  console.error(error);
  process.exit(-1);
});

server.on("error", function(error) {
  if (error.syscall !== "listen") {
    throw error;
  }

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case "EACCES":
      console.error(serverConfig.port + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(serverConfig.port + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
});
