// ! Imports
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");
const { dev, allMusic, music, port, socials, name } = require("./c");
const redis = require("ioredis");
const { promisify } = require("util");

const {
  compileSassAndSaveMultiple,
  setupCleanupOnExit,
} = require("compile-sass");
const path = require("path");
// Init
const app = express();
const r = new redis(6379, "192.168.1.11", {
  connectionName: `ALEXHELDT${dev ? "-dev" : ""}`,
});
const get = promisify(r.get).bind(r);
compileSassAndSaveMultiple({
  sassPath: path.join(__dirname, "assets/sass/"),
  cssPath: path.join(__dirname, "assets/css/"),
  files: ["index.sass"],
});

process.on("SIGINT", () => {
  try {
    setupCleanupOnExit("assets/css");
    console.log("worked");
    process.exit(0);
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
});

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());
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(" ");
  })
);

app.get("/", async (req, res) => {
  res.render("index", {
    layout: "index",
    name,
    protocol: dev ? `http` : `https`,
    host: dev ? `${req.hostname}:${port}` : `${req.hostname}`,
    socials,
    music,
    creator: {
      name: (await r.get("creator_name")) || "lio",
      website: (await r.get("creator_website")) || "https://himbo.cat",
    },
  });
});

// ! SOCIAL LINKS
socials.forEach((social) => {
  app.get(`/${social.name}`, (req, res) => res.redirect(social.link));
});

// ! MUSIC LINKS
allMusic.forEach((item) => {
  app.get(`/${item.id}`, (req, res) => res.redirect(item.link));
});

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