const express = require("express");
const path = require("path");
const hbs = require("hbs");
const bodyParser = require("body-parser");
const db = require("./models");
const cluster = require("cluster");
const os = require("os");
require("dotenv").config();
const routeHandler = require("./src/routes/index");
const cookieSession = require("cookie-session");

if (cluster.isMaster) {
  // Fork workers
  const numCPUs = os.cpus().length;
  console.log(`Master process is running on PID: ${process.pid}`);
  console.log(`Forking ${numCPUs} workers...`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // Listen for dying workers
  cluster.on("exit", (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
    console.log("Starting a new worker");
    cluster.fork();
  });
} else {
  // Worker processes
  const app = express();

  // SET PARTIALS FOLDER
  const partialpath = path.join(__dirname, "./src/views/partials");

  // SET VIEWS AND VIEW ENGINE
  app.set("views", "./src/views");
  app.set("view engine", "ejs");
  hbs.registerPartials(partialpath);

  // Cache options
  const cacheOptions = {
    etag: true,
    maxAge: 86400000, // 1 day
    redirect: true,
    setHeaders: function (res, path, stat) {
      res.set({
        "x-timestamp": Date.now(),
        gbola: "hi",
        "Cache-Control": path.includes("index.html")
          ? "no-store"
          : "public, max-age=86400000",
      });
    },
  };

  // SET STATIC FOLDER AND PUBLIC FOLDER WITH CACHING
  app.use("/", express.static(path.join(__dirname, "public"), cacheOptions));
  app.use(
    "/css",
    express.static(path.join(__dirname, "public/css"), cacheOptions)
  );
  app.use(
    "/css2",
    express.static(path.join(__dirname, "public/admin/css"), cacheOptions)
  );
  app.use(
    "/avatar",
    express.static(path.join(__dirname, "libaries/avatar"), cacheOptions)
  );
  app.use(
    "/project",
    express.static(path.join(__dirname, "project"), cacheOptions)
  );
  app.use(
    "/student-project",
    express.static(path.join(__dirname, "libaries/projects"), cacheOptions)
  );
  app.use(
    "/js",
    express.static(path.join(__dirname, "public/js"), cacheOptions)
  );
  app.use(
    "/js2",
    express.static(path.join(__dirname, "public/admin/js"), cacheOptions)
  );
  app.use(
    "/img",
    express.static(path.join(__dirname, "public/img"), cacheOptions)
  );
  app.use(
    "/img2",
    express.static(path.join(__dirname, "public/admin/img"), cacheOptions)
  );
  app.use(
    "/image",
    express.static(path.join(__dirname, "public/assets/Image"), cacheOptions)
  );
  app.use(
    "/vendors",
    express.static(path.join(__dirname, "public/vendors"), cacheOptions)
  );
  app.use(
    "/vendors2",
    express.static(path.join(__dirname, "public/admin/vendors"), cacheOptions)
  );
  app.use(
    "/assets",
    express.static(path.join(__dirname, "public/assets"), cacheOptions)
  );

  // URL ENCODE
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  app.use(express.json());

  app.use(
    cookieSession({
      name: "session",
      keys: [process.env.SESSION_SECRET],
      maxAge: 24 * 60 * 60 * 1000, // 1 day
    })
  );

  routeHandler(app);

  const port = process.env.PORT || 4000;

  app.listen(port, () =>
    console.log(`Worker ${process.pid} listening to port ${port}`)
  );
}
