
<!----------------------------------------------------
	File:  LessonRequests.vue
	Author: William Karpinski
	Scope: Extension Horaire
	Description: Lessons Management Page for the secretary
----------------------------------------------------->

<script setup>

import { ref } from 'vue'
import i18n from '@/i18n.js'
import {formatDate,getHoursMinutes, invertedFormatDate, createLessonEvent} from '../scheduleFunctions.js'
import {getAllSchedule, deleteLessonFromSchedule ,getSchedule, createSchedule} from "@/rest/scheduleRest.js";
import {getLessons, createLesson, alterLesson, deleteLesson} from "@/rest/lessonSchedule.js"
import {getTeachers} from "@/rest/Users.js"
import {getcurriculum, getAllCurriculums} from "@/rest/curriculum.js"

  const trueSchedule = ref()
  const schedule = ref();
  const lessonFinder = ref();
  const curriculum = ref();
  const allSchedules = ref(await getAllSchedule());
  const filter = ref("null");
  const subFilter = ref("null");
  const filters = ["Type","Teacher","Course"];
  const types = ["TP","TD","Course","Exam"];
  const locals = ["A0B1","A1B1","A2B1","A0B2"]
  const teachers = await getTeachers() ;
  const allCurriculum = ref();
  const courses = ref();

  const createScheduleMod = ref(false);
  const createMod = ref(false);
  const deleteMod = ref(false);

const colors = {"TP":"rgb(36,175,255)","TD":"rgb(255,36,175)","Exam":"rgb(175,255,36)","Course":"rgb(255,36,175)"}
const currentDate = new Date();

const editElementID = ref();

const maxDate = ref(invertedFormatDate(new Date([currentDate.getMonth()<7 ? currentDate.getFullYear() : (currentDate.getFullYear())+1],7,31)));

const minDate = ref(invertedFormatDate((new Date()).setDate(currentDate.getDate()+1)))


  const pattern = {
    "course": null,
    "day":null,
    "lessonStart": null,
    "lessonEnd": null,
    "lessonType": null,
    "local": null,
    "color": null,
  }

  const lessonCreator = {
    "courseId" : null,
    "lessonStart":null,
    "lessonEnd":null,
    "lessonType":null,
    "local":null,
    "color":null,
  }

  const patternModify = {
    "day": null,
    "lessonStart": null,
    "lesssonEnd": null,
    "local":null,
    "lessonType":null,
  }


/*
 * Sets up allCurriculum to contain only the curriculums that don't have any schedule
 */
async function setCurriculum(){
  const temp = await getAllCurriculums();
  let isIn = false;
  let toReturn =[] ;
  for (let element in temp){
    for (let item in allSchedules.value){
      console.log(allSchedules.value[item])
      console.log(temp[element])
      if((allSchedules.value[item].curriculum.option == temp[element].option) && (allSchedules.value[item].curriculum.year == temp[element].year)){

            isIn = true;
            break;
      }
    }
    if(!isIn){
      toReturn.push(temp[element])
    }
    isIn = false;
  }
  allCurriculum.value = toReturn.slice();
}


const toModify = ref(Object.assign({}, pattern));
  const lessonBuffer = ref(Object.assign({}, pattern));
  const lessonCreatorBuffer = ref(Object.assign({},lessonCreator));


  function setModify(lesson){
    toModify.value.day = invertedFormatDate(new Date(lesson.lessonStart));
    toModify.value.lessonStart = getHoursMinutes(lesson.lessonStart);
    toModify.value.lessonEnd = getHoursMinutes(lesson.lessonEnd);
    toModify.value.local = lesson.local;
    toModify.value.lessonType = lesson.lessonType;
  }

  function inFuture(lesson){
    let toCompare = new Date(lesson.lessonStart);
    let current = new Date();
    return (current < toCompare)
}

async function setCourses(){
  courses.value = (await getcurriculum(curriculum.value.curriculumId)).courses
}

/*
 * Sort the lessons via a criteria
 */
  function sortSchedule(){
    schedule.value =trueSchedule.value.lessons;
    if(filter.value =="Teacher"){
      schedule.value = sortByTeacher(schedule.value,subFilter.value);

    }
    else if(filter.value =="Type"){
      schedule.value = sortByType(schedule.value,subFilter.value);
    }
    else if(filter.value =="Course"){
      schedule.value = sortByCourse(schedule.value,subFilter.value);
    }
  }

  function sortByType(lessons,type){
    if(type == null){
      return lessons;
    }
    const matrix = [];
    for (let element in lessons){
      if(lessons[element].lessonType == type){
        matrix.push(lessons[element])
      }
    }
    return matrix
  }

  function sortByCourse(lessons,course){
    if(course == null){
      return lessons;
    }
    const matrix = [];
    for (let element in lessons){
      if(lessons[element].course.courseId == course.courseId){
        matrix.push(lessons[element])
      }
    }
    return matrix
  }

  function sortByTeacher(lessons, teacher){
    if(teacher == null){
      return lessons;
    }
    const matrix = [];
    for (let element in lessons){
      if(lessons[element].course.owner.regNo == teacher.regNo){
        matrix.push(lessons[element])
      }
    }
    return matrix
  }

  /*
   * Change the schedule filter
   */
  async function changeSchedule(){
      schedule.value =trueSchedule.value.lessons;
      curriculum.value = trueSchedule.value.curriculum;
          
      courses.value = (await getcurriculum(curriculum.value.curriculumId)).courses;
      filter.value = "null";
      subFilter.value = "null"
  }


 async function newLesson(){
    let isnull = false;
    if (lessonBuffer.value.lessonType != null){
      lessonBuffer.value.color = colors[lessonBuffer.value.lessonType];
      for(let element in lessonBuffer.value){
        if(lessonBuffer.value[element] == null){
          isnull=true;
          break;
        }
        }
      if(!isnull){

        let start = createLessonEvent(lessonBuffer.value.day,lessonBuffer.value.lessonStart)
        let end = createLessonEvent(lessonBuffer.value.day,lessonBuffer.value.lessonEnd)

        lessonCreatorBuffer.value.lessonStart = start;
        lessonCreatorBuffer.value.lessonEnd = end;
        lessonCreatorBuffer.value.color = lessonBuffer.value.color;
        lessonCreatorBuffer.value.lessonType =lessonBuffer.value.lessonType;
        lessonCreatorBuffer.value.local = lessonBuffer.value.local;
        lessonCreatorBuffer.value.courseId = lessonBuffer.value.course.courseId;
        
       await createLesson(lessonCreatorBuffer.value);

        lessonFinder.value = await getLessons();

      }
    }
    lessonBuffer.value = Object.assign({}, pattern);
    lessonFinder.value = null;
    lessonCreatorBuffer.value = Object.assign({},lessonCreator)
    trueSchedule.value = null;

  }

  /*
    * Modify a lesson
   */

async function patchLesson(lesson){
  
  for (let element in toModify.value){
      if (element =="lessonType" && (toModify.value[element] != lesson[element])){
        await alterLesson(lesson.lessonID,{lessonType:toModify.value[element]});
      }
      if (element =="local" && (toModify.value[element] != lesson[element])){
        await alterLesson(lesson.lessonID,{local:toModify.value[element]});
      }
      if (element =="lessonStart" && (toModify.value[element] != lesson[element])){
        await alterLesson(lesson.lessonID,{lessonStart:createLessonEvent(toModify.value.day,toModify.value[element])
});
      }
      if (element =="lessonEnd" && (toModify.value[element] != lesson[element])){
        await alterLesson(lesson.lessonID,{lessonEnd:createLessonEvent(toModify.value.day,toModify.value[element])
});
      }
      if(element == "day" && (toModify.value[element] != invertedFormatDate(new Date(lesson.lessonStart))) ){
        
       if(toModify.value.lessonStart == lesson.lessonStart){
        await alterLesson(lesson.lessonID,{lessonStart:createLessonEvent(toModify.value.day,lesson.lessonStart)
      });}
       if(toModify.value.lessonEnd == lesson.lessonEnd){
          await alterLesson(lesson.lessonID,{lessonStart:createLessonEvent(toModify.value.day,lesson.lessonStart)});
      }
    }
       }
    toModify.value= Object.assign({},patternModify);
    trueSchedule.value = await getSchedule(trueSchedule.value.scheduleId);
    schedule.value =trueSchedule.value.lessons;
    editElementID.value= '';
}



  async function removeLesson() {
      await deleteLessonFromSchedule(trueSchedule.value.scheduleId, editElementID.value)
      await deleteLesson(editElementID.value);
      trueSchedule.value = await getSchedule(trueSchedule.value.scheduleId);
      schedule.value =trueSchedule.value.lessons;
      editElementID.value= '';

}
/*
 * Create a new Schedule
 */
  async function newSchedule(){
    await createSchedule(curriculum.value);
    allSchedules.value = await getAllSchedule();
    setCurriculum();
  }


</script>
<template>
  <div class="body">
    <div class="listTitle buttonGrid"v-if="!createMod && !createScheduleMod" >
      <button class="create" @click="setCurriculum();createScheduleMod = true"> {{i18n("schedule.createSchedule")}}</button>
      <button class="create" @click="createMod = true;">{{i18n("schedule.createLesson")}}</button>
      <button class="delete" @click="deleteMod = !deleteMod;">{{!deleteMod ? i18n("schedule.deleteMod") : i18n("schedule.noDeleteMod")}}</button>

    </div>
    <div v-if="createMod">
      <form class="listElement" style="width:40%; margin:0 auto 0 auto;">
        <div style="margin-bottom:20px;">
         {{i18n("schedule")}} :
          <select @change="setCourses()"v-model="curriculum">
            <option v-for="item in allSchedules" :value='item.curriculum'>{{item.curriculum.option}} - {{item.curriculum.year}}</option>
          </select>
        </div>
        <div style="margin-bottom:20px;">
          {{i18n("Course")}} :
         <select v-if="curriculum != null" v-model="lessonBuffer.course">
            <option v-for="item in courses" :value='item'>{{item.title}}</option>
          </select>
        </div>
        <div style="margin-bottom:20px;">
          {{i18n("day")}}:
          <input type="date" :min="minDate" :max="maxDate" v-model="lessonBuffer.day">
        </div>
        <div style="margin-bottom:20px;">
          {{i18n("start")}}:
          <input v-model="lessonBuffer.lessonStart" type="time" min="08:00" max="18:00" required />
        </div>
        <div style="margin-bottom:20px;">
          {{i18n("end")}}:
          <input v-model="lessonBuffer.lessonEnd" type="time" min="10:00" max="20:00" required />
        </div>
        <div style="margin-bottom:20px;">
          Type:
          <select v-model="lessonBuffer.lessonType">
           <option v-for="item in types" :value='item'>{{item}}</option>
          </select>
        </div>
        <div style="margin-bottom:20px;">
          Local: 
          <select v-model="lessonBuffer.local">
           <option v-for="item in locals" :value='item'>{{item}}</option>
          </select>
        </div>

      <button class="create" @click="createMod=!createMod; newLesson();"> {{i18n("courses.confirm")}} </button>
      <button style="float:right;" @click="createMod=!createMod">{{i18n("courses.back")}}</button>
      </form>
    </div>

        <div v-if="createScheduleMod">
        <form class="listElement" style="width:40%; margin:0 auto 0 auto;">
          <div style="margin-bottom:20px;">
            {{i18n("schedule")}} :
            <select v-model="curriculum">
              <option v-for="item in allCurriculum" :value='item'>{{item.option}} - {{item.year}}</option>
            </select>
          </div>
          <button class="create" @click="createScheduleMod=!createScheduleMod ;newSchedule();"> {{i18n("courses.confirm")}} </button>
          <button style="float:right;" @click="createScheduleMod=!createScheduleMod;">{{i18n("courses.back")}}</button>
        </form>
      </div>



    <div v-if="!createMod && !createScheduleMod">
      <select @change="changeSchedule()" v-model="trueSchedule">
        <option v-for="item in allSchedules" :value='item'>{{item.curriculum.option}} - {{item.curriculum.year}}</option>
      </select>
      <select v-if="schedule != null" @change="subFilter = 'null'" v-model="filter">
        <option :value ="null">No Filter</option>
        <option v-for="item in filters" :value="item">{{i18n(item.toString())}}</option>
      </select>
      <select @change="sortSchedule()" v-if="filter == 'Teacher'" v-model="subFilter">
        <option :value ="null">No Filter</option>
        <option v-for="item in teachers" :value=item>{{item.lastName}}</option>
      </select>
      <select @change="sortSchedule()"  v-if="filter == 'Course'" v-model="subFilter">
        <option :value ="null">No Filter</option>
        <option v-for="item in courses" :value=item>{{item.title}}</option>
      </select>
      <select @change="sortSchedule()" v-if="filter == 'Type'" v-model="subFilter">
        <option :value ="null">No Filter</option>
        <option v-for="item in types" :value='item'>{{item}}</option>
      </select>

    </div>
    <div v-if="!createMod && !createScheduleMod" :key="element.lessonID" v-for="element in schedule" style="width:50%;margin-left:auto; margin-right:auto;" >
        <div  v-if="editElementID !== element.lessonID" style ="padding:15px 15px 15px 15px;">
        <button  v-if="inFuture(element)" @click="editElementID = element.lessonID;setModify(element);">
        {{i18n("courses.modify")}}
        </button>
      </div>
      <div v-else>
        <button @click="patchLesson(element);"> {{i18n("courses.confirm")}} </button>
        <button @click="editElementID= '';"> {{i18n("courses.back")}} </button>
      </div>
      <div class="listElement">
        <div  v-if="editElementID != element.lessonID">
          <div>
          {{element.course.title}}
          </div>
          <div>{{formatDate(element.lessonStart)}}</div>
          <div>{{getHoursMinutes(element.lessonStart)}}-{{getHoursMinutes(element.lessonEnd)}}
          </div>
          <div>{{element.local}}</div>
          <div>{{element.lessonType}}</div>
        </div>

        <div v-else>
         <div>{{element.course.title}}</div>
        <div style="margin-bottom:20px;">
          Day:
          <input type="date" :min="minDate" :max="maxDate" v-model="toModify.day">
        </div>
        <div style="margin-bottom:20px;">
          Start: 
          <input v-model="toModify.lessonStart" type="time" min="8:00" max="20:00"/>
        </div>
        <div style="margin-bottom:20px;">
          End: 
          <input v-model="toModify.lessonEnd" type="time" min="10:00" max="20:00" required />
        </div>
        <div style="margin-bottom:20px;">
          Type: 
          <select v-model="toModify.lessonType">
           <option v-for="item in types" :value='item'>{{item}}</option>
          </select>
        </div>
        <div style="margin-bottom:20px;">
          Local: 
          <select v-model="toModify.local">
           <option v-for="item in locals" :value='item'>{{item}}</option>
          </select>
        <div v-if="deleteMod" style="float:right;">
            <button class="delete" @click="removeLesson(element);"> {{i18n("courses.deleteCourse")}} </button>
        </div>
        
        </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.body {
    width:100%;
    margin-top:3.5%;
  }

.listElement{
 min-width:625px;
  border:2px solid black;
  font-size:25px;
  color:white;
  padding:20px;
  background-color:rgb(50,50,50);
  border-radius:20px;
  margin-bottom:10px;

}

  input, select{
  padding:10px 10px 10px 10px; 
  font-size:25px;
  cursor: pointer;
  border:none;
  border-radius:15px;
  }
  button{
    font-size:15px;
     height:50px;
     width:100px;
    border:none;
    border-radius:20px;

  }

  .buttonGrid{
    display:grid;
    grid-template-columns: auto auto;
    column-gap:50px;
    grid-template-areas:
      "create delete";
  }

  .create{
    grid-area:create;
    
    background-color:rgb(0,200,0);

  }

  .delete{
    grid-area:delete;
    background-color:rgb(200,0,0);
  }

  .listTitle{
    min-width:380px;
    display: flex;
    justify-content: center;
    align-items: center;
    width:25%;
    margin-left:auto;
    margin-right:auto;
    border:2px solid black;
    font-size:25px;
    color:white;
    padding:20px;
    background-color:rgb(50,50,50);
    border-radius:20px;
    margin-bottom:10px;

    button:hover{
      opacity:0.8;
    }
}
</style>
