import { Cours } from "../classes/cours";
import { Etudiant } from "../classes/etudiant";
import { HoraireCours } from "../classes/horaireCours";
import { Utilisateur } from "../models/utilisateur";
import { api } from "../utils/define";

export class CoursControlleur {
  private _cours: Cours[] = new Array();

  public recupererCours(user: Utilisateur) {
    try {
      return this._cours.filter(cours => cours.getEnseignantId() === user.id);
    } catch (error) {
      console.warn(error.message);      
    }
  }

  public recupererCoursDetails(id: string) {
    try {
      const cours_courant = this._cours.find((x) => x.group_id === id);
      return cours_courant;
    } catch (error) {
      console.warn(error.message);      
    }
  }

  public retirerCours(id: string) {
    try {
      this._cours.find((x) => x.group_id === id).setEtat(false);
    } catch (error) {
      console.warn(error.message);      
    }
  }

  public ajouterCours(id: string) {
    try {
      this._cours.find((x) => x.group_id === id).setEtat(true);
    } catch (error) {
      console.warn(error.message);      
    }
  }

  public async init() {
    try{
    this._cours = [];
    const coursRes = await api("/api/v3/course/all", {});
    const schedulesRes = await api("/api/v3/schedule/all", {});
    const studentsGroupsRes = await api("/api/v3/student/groupstudent", {});
    const studentsRes = await api("/api/v3/student/all", {});

    let schedules = [];
    schedulesRes.body.data.forEach((schedule) => {
      const scheduleHoraireCours = new HoraireCours(
        schedule.group_id,
        schedule.day,
        schedule.hours,
        schedule.activity,
        schedule.mode,
        schedule.local,
        schedule.teacher_id
      );
      
      schedules.push(scheduleHoraireCours)
    });


    schedules.forEach((schedule) => {
      const students = studentsGroupsRes.body.data
        .filter((unStudent) => unStudent.group_id === schedule.group_id)
        .map(
          (item) => new Etudiant(
              item.student_id,
              studentsRes.body.data.find(
                (student) => student.id === item.student_id
              ).first_name,
              studentsRes.body.data.find(
                (student) => student.id === item.student_id
              ).last_name
            )
        );

      const cours = coursRes.body.data.find(
        (c) => c.id === schedule.group_id.split("-")[1]
      );

      if (schedule.activite === "C") {
        this._cours.push(
          new Cours(
            cours.id,
            schedule.group_id,
            cours.prealable,
            cours.titre,
            students,
            schedules.filter(x => x.group_id === schedule.group_id)
          )
        );
      }
    });

    }catch(e){
      console.warn(e.message);
    }
  }
}
