import express from "express";
import ExpressSession from "express-session";
import logger from "morgan";
import flash from "express-flash-plus";
import { cookieParser } from "./utils/define";

import { viewRouter } from "./routes/viewRouter";
import { loginRouter } from "./routes/loginRouter";
import { baseRouter } from "./routes/indexRouter";
import { coursRouter } from "./routes/coursRouter";
import { questionRouter } from "./routes/questionRouter";
import { questionnaireRouter } from "./routes/questionnaireRouter";
import { initControllers } from "./locator";
import { devoirRouter } from "./routes/devoirRouter";

// Creates and configures an ExpressJS web server.
class App {
  // ref to Express instance
  public expressApp: express.Application;

  //Run configuration methods on the Express instance.
  constructor() {
    console.info("constructing App...");
    this.expressApp = express();
    this.expressApp.use(cookieParser());
    initControllers.then(() => {
      this.middleware();
      this.routes();
      this.expressApp.set("view engine", "pug");
      this.expressApp.use(
        express.static(__dirname + "/public") as express.RequestHandler
      ); // https://expressjs.com/en/starter/static-files.html
    })
  }

  // Configure Express middleware.
  private middleware(): void {
    console.info("middleware setup...");
    this.expressApp.use(logger("dev") as express.RequestHandler);
    this.expressApp.use(express.json() as express.RequestHandler);
    this.expressApp.use(
      express.urlencoded({ extended: false }) as express.RequestHandler
    );
    this.expressApp.use(
      ExpressSession({
        secret: "MUCBBrM09VeslYW8HO9mQJ1tZcJJnj9jgYPQ8941",
        resave: false,
        saveUninitialized: true,
      })
    );
    this.expressApp.use(flash());
  }

  private routes(): void {
    console.info("routes setup...");
    this.expressApp.use("/", baseRouter.router); // routage de base
    this.expressApp.use("/", viewRouter.router);
    this.expressApp.use("/questions", questionRouter.router);
    this.expressApp.use("/questionnaires", questionnaireRouter.router);
    this.expressApp.use("/questions", questionRouter.router)
    this.expressApp.use("/devoir", devoirRouter.router)
    this.expressApp.use("/api/v1/auth", loginRouter.router);
    this.expressApp.use("/api/v1/cours", coursRouter.router);
  }
}

export default new App().expressApp;
