//! Deps
const express = require("express");
const helmet = require("helmet");
const compression = require("compression");
const cors = require("cors");
const morgan = require("morgan");
const chalk = require("chalk");
const hbs = require("express-handlebars");
let { port, hostname } = {
  port: 18726,
};
const con = require("./constants");

const app = express();

app.engine(
  "hbs",
  hbs({
    extname: "hbs",
    defaultView: "default",
  })
);

app.set("view engine", "hbs");
app.set("json spaces", 4);
app.use("/assets", express.static("./assets"));
app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);
app.use(helmet());
app.use(compression());
app.use(cors());
// Logging
app.use(
  morgan((tokens, req, res) => {
    return [
      chalk.hex("#34ace0").bold(`[ ${tokens.method(req, res)} ]`),
      chalk.hex("#ffb142").bold(tokens.status(req, res)),
      chalk.hex("#ff5252").bold(req.hostname + tokens.url(req, res)),
      chalk.hex("#2ed573").bold(tokens["response-time"](req, res) + "ms"),
      chalk.hex("#f78fb3").bold("@ " + tokens.date(req, res)),
    ].join(" ");
  })
);

function breakSocials(social) {
  // if (typeof social !== String) throw new Error('This social media is not a string :eyes:')
  return social.split("");
}

module.exports = (async) => {
  app.get("/", async (req, res) => {
    res.render("index", {
      layout: "main",
      name: con.name,
      host: req.hostname,
      social: [
        {
          name: "Twitter",
          link: "bastard.ink/twitter",
          character: breakSocials("Twitter"),
        },
        {
          name: "Discord",
          link: "bastard.ink/discord",
          character: breakSocials("Discord"),
        },
        {
          name: "Commissions",
          link: "bastard.ink/commissions",
          character: breakSocials("Commissions"),
        },
        {
          name: "Trello",
          link: "bastard.ink/trello",
          character: breakSocials("Trello"),
        },
        {
          name: "Ko-Fi",
          link: "bastard.ink/kofi",
          character: breakSocials("Ko-Fi"),
        },
      ],
    });
  });

  app.get("/commissions", (req, res) => {
    res.redirect(con.socials.comms);
  });
  app.get("/twitter", (req, res) => {
    res.redirect(con.socials.twitter);
  });
  app.get("/discord", (req, res) => {
    res.redirect(con.socials.discord);
  });
  app.get("/trello", (req, res) => {
    res.redirect(con.socials.trello);
  });
  app.get("/kofi", (req, res) => {
    res.redirect(con.socials.kofi);
  });

  app.listen(port /* , hostname */, () => {
    console.log(`[ Server ] Listening on ${port}`);
  });
};
