#!/usr/bin/env node
"use strict";

const http = require("http");
const moment = require("moment");
const { assign, toLower } = require("lodash");

const config = require("./config");
const { express, logger, models } = require("./core");

const currentState = assign(
  {
    launchedAt: Date.now(),
    appPath: process.cwd(),
    //host: process.env.HOST || process.env.HOSTNAME || 'localhost',
    //port: process.env.PORT || 19999,
    environment: toLower(process.env.NODE_ENV) || "development",
    connections: {},
  },
  config
);

function stop(server) {
  // Destroy server and available connections.
  if (server) {
    server.close();
  }

  process.send("stop");
  // Kill process.
  process.exit(1);
}

moment.locale("es");
const server = http.createServer(express);
server.on("connection", (conn) => {
  const key = conn.remoteAddress + ":" + conn.remotePort;
  currentState.connections[key] = conn;

  conn.on("close", () => {
    delete currentState.connections[key];
  });
});

server.on("error", (err) => {
  if (err.code === "EADDRINUSE") {
    logger.debug(`⛔️ Server wasn't able to start properly.`);
    logger.error(`The port ${err.port} is already used by another application.`);
    stop(server);
    return;
  }

  console.error(err);
});

try {
  models.sequelize.sync({ force: false }).then(() => {
    // Launch server.
    server.listen(currentState.server.port, (err) => {
      if (err) {
        logger.debug(`⚠️ Server wasn't able to start properly.`);
        logger.error(err);
        return stop(server);
      }

      logger.info("Time: " + moment().toISOString());
      logger.info("Launched in: " + (moment() - currentState.launchedAt) + " ms");
      logger.info("Environment: " + currentState.environment);
      logger.info("Process PID: " + process.pid);
      //logger.info(`Version: ${this.config.info.strapi} (node v${this.config.info.node})`);
      logger.info("To shut down your server, press <CTRL> + C at any time");
      logger.info(`⚡️ Server: http://${currentState.server.hostname}:${currentState.server.port}`);
    });
  });
} catch (err) {
  logger.debug(`⛔️ Server wasn't able to start properly.`);
  logger.error(err);
  console.error(err);
  stop(server);
}
