import { Router, Request, Response, NextFunction } from "express";
import { CoursControlleur } from "../controleurs/coursControleur";
import { authenticate } from "../middlewares/authenticate";
import { errorCode500 } from "../utils/errors";
import { authorizeEnseignant } from "../middlewares/authorizeEnseignant";
import { coursController } from "../locator";

export class CoursRouter {
  private _router: Router;

  get router() {
    return this._router;
  }

  constructor() {
    this._router = Router();
    this.init();
  }

  public recupererListeCours(req: Request, res: Response, next: NextFunction) {
    try {
      res.status(200).json(coursController.recupererCours(req.body.user));
    } catch (error) {
      errorCode500(error, req, res);
    }
  }

  public retirerCours(req: Request, res: Response, next: NextFunction) {
    try {
      const id = req.params.id;
      coursController.retirerCours(id);
      res.status(200).json(coursController.recupererCours(req.body.user));
    } catch (error) {
      errorCode500(error, req, res);
    }
  }

  public recupererCours(req: Request, res: Response, next: NextFunction) {
    try {
      const id = req.params.id;
      res.status(200).json(coursController.recupererCoursDetails(id));
    } catch (error) {
      errorCode500(error, req, res);
    }
  }

  public ajouterCours(req: Request, res: Response, next: NextFunction) {
    try {
      const id = req.body.group_id;
      coursController.ajouterCours(id)
      res.status(200).json(coursController.recupererCours(req.body.user));
    } catch (error) {
      errorCode500(error, req, res);
    }
  }

  init() {
    this._router.get("", authenticate, this.recupererListeCours.bind(this));
    this._router.delete(
      "/:id",
      authenticate,
      authorizeEnseignant,
      this.retirerCours.bind(this)
    );
    this._router.get("/:id", authenticate, this.recupererCours.bind(this));
    this._router.post(
      "",
      authenticate,
      authorizeEnseignant,
      this.ajouterCours.bind(this)
    );
  }
}

export const coursRouter = new CoursRouter();
