<script setup>
  import {reactive, ref } from 'vue'
  import i18n from '@/i18n.js'
  import {login, register, disconnect, isLogged} from '@/rest/Users.js'
  import {getAllCurriculums, getcurriculum} from '@/rest/curriculum.js'
  import { uploadProfilePicture } from '@/rest/uploads.js'
  import {toast} from 'vue3-toastify'
  import 'vue3-toastify/dist/index.css';
  import {createExternalCurriculum} from "@/rest/externalCurriculum.js";

  const loginPage= ref(true)
  const page = ref(0)

  const outputs = reactive({
    surname:null,
    firstname:null,
    password:null,
    birthday:null,
    email:null,
    address:null,
    country:null,
    curriculum:null,
    equivalenceState: "Unrequired"
  })

  const notcompletedCheck = ref(false);

  const externalCurr = reactive({
    inscriptionRequestId : null,
    school:null,
    formation :null,
    completion : null,
    startYear : null,
    endYear: null,
    justifdocUrl : null
  })

  //Stores some externalCurriculums in order to upload them all at the confirmation of the registration request
  const externalCurrTab = ref([]);

  const submitValue= ref(i18n("login.guest.submit"))
  const passwordConfirm=ref("")
 
  const imageSaved = ref(false)
  let ppData = ""

  //Contains the id of the newly created request (useful to link the student's formations informations to the request)
  let requestId = ""

  const curricula= await getAllCurriculums();
  
  function goBackHome(){
    setTimeout(() => {
      window.location.href="#/home";
      }, "500");
  }
  function verifyInputs(pass){
    if(pass==passwordConfirm.value){
      page.value++;
      return toast('Password and Confirm Password are correct.', {
      
    type: "success",});
    }
    else{
    return toast('Password and Confirm Password are different',{type: "error",});
    }
  }
  if (isLogged()){
  disconnect();
  window.location.reload();}

  async function uploadPP(arg){
    const data = await uploadProfilePicture(arg);
    ppData = data.url;
  }

  //This functions makes the distinction between a master cursus (year 4 or more) and a bachelor cursus (year 3 or less)
  function getCursusDisplay(cursus){
    if (cursus.year <= 3){
      return "BAB " + cursus.year + " " + cursus.option;
    }else{
      return "MA" + (parseInt(cursus.year)-3).toString() + " " + cursus.option;
    }
  }

  //Post the register request and return the id of the newly created request and also post the external curriculum list in the database
  async function postRegisterReq(){
    const val = await register(outputs.firstname, outputs.surname, outputs.birthday, outputs.password, outputs.email, outputs.address, outputs.country, outputs.curriculum, ppData, null, new Date(), outputs.equivalenceState);
    for (let item in externalCurrTab.value){
      await createExternalCurriculum(val.id, externalCurrTab.value[item].school, externalCurrTab.value[item].formation, externalCurrTab.value[item].completion, externalCurrTab.value[item].startYear, externalCurrTab.value[item].endYear, externalCurrTab.value[item].justifdocUrl);
    }
  }


  function deleteExtCursus(extcursus){
    externalCurrTab.value.splice(externalCurrTab.value.indexOf(extcursus),1)
  }
</script>


<template>
    <div class="setup">
      <div v-if="loginPage">
      <div class='loginBox' style="margin-top:30%;">
          <form @submit.prevent="login(outputs.email,outputs.password);goBackHome();"class="form">
            <h1 style="color:rgb(239,60,168); font-family: sans-serif;">
              {{i18n("login.guest.signin")}}
            </h1>
            <div class="inputBox">
              <p>ID / {{i18n("login.guest.email")}}</p> 
              <input type="text" v-model="outputs.email">
            </div>
            <div class="inputBox">
              <p>{{i18n("login.guest.password")}}</p>
              <input type="password" v-model="outputs.password">
            </div>
            <div class="register">
              <a @click="loginPage=!loginPage">{{i18n("login.guest.register")}}</a>
            </div>
            <div class="inputBox" style="margin-bottom:35px;">
              <input type="submit" v-model="submitValue">
            </div>
          </form>
        </div>
      </div>
        <div v-else>
          <div class='loginBox' style="margin-top:30%; margin-bottom:50%;">
            <form class="form">
            <h1 style="color:rgb(239,60,168); font-family: sans-serif; text-align:center;">
              {{i18n("login.guest.welcome")}}
            </h1>
            <div v-if="page === 0">
              <div class="inputBox">
                <p>{{i18n("login.guest.surname")}}</p>
                <input type="text" v-model="outputs.surname">
              </div>
              <div class="inputBox">
                <p>{{i18n("login.guest.firstname")}}</p>
                <input type="text" v-model="outputs.firstname">
              </div>
              <div class="inputBox">
                <p>{{i18n("login.guest.birthday")}}</p>
                <input type="date" v-model="outputs.birthday">
              </div>
              <div class="inputBox">
                 <p>{{i18n("login.guest.password")}}</p>
                 <input type="password" v-model="outputs.password">
              </div>
              <div class="inputBox">
                <p>{{i18n("login.guest.confirm")}} {{i18n("login.guest.password")}}</p>
                 <input type="password" v-model="passwordConfirm">
              </div>
              
              <div class="switchpage">
                <button @click="verifyInputs(outputs.password);">{{i18n("login.guest.nextpage")}}</button>

              </div>
              <div @click="(loginPage=!loginPage) && (page=0)" class="register">
                <a>{{i18n("login.guest.alregister")}}</a>
              </div>
            </div>
            <div v-if="page === 1">
              <div class="inputBox">
                <p>{{i18n("login.guest.email")}}</p>
                <input type="mail" v-model="outputs.email">
              </div>
              <div class="inputBox">
                <p>{{i18n("login.guest.address")}}</p>
                <input type="text" v-model="outputs.address">
              </div>
              <div class="inputBox">
                <p>{{i18n("login.guest.country")}}</p>
                <input type="text" v-model="outputs.country">
              </div>
              <form class="inputBox" novalidate enctype="multipart/form-data">
              	<p>{{i18n("profile.picture").toUpperCase()}}</p>
              </form>
              <label class="browser">
                Parcourir . . .
				        <input  type="file" :disabled="imageSaved" @change="ppData = uploadProfilePicture($event.target.files); imageSaved = true;" accept="image/*">
              </label>
              <form novalidate enctype="multipart/form-data" class="inputBox">
              	<p>{{i18n("profile.picture").toUpperCase()}}</p>
				        <input type="file" @change="uploadPP($event.target.files); imageSaved = true;" accept="image/*">
              </form>
              <div class="inputBox">
                <p>{{i18n("Curriculum").toUpperCase()}}</p> 
                  <select v-model="outputs.curriculum">
                    <option v-for="item in curricula" :value="item.curriculumId">{{getCursusDisplay(item)}}</option>
                  </select>
              </div>
              <p style="color:rgb(239,60,168);">
                Si vous êtes déja inscrits dans cette université veuillez vous connecter a votre compte et utilisez les fonctions
                changer de cursus/réinscription sinon continuez ici.
              </p>
              <div style="align-self:center;" class="inputBox">
                <button style="margin-top:25px;" @click="page++;">
                  {{i18n("login.guest.nextpage")}}
                </button>
              </div>
              <div  class="switchpage">
                <button @click="page--">{{i18n("login.guest.lastpage")}}</button>
              </div>
              <div  @click="(loginPage=!loginPage) && (page=0)" class="register">
                <a>{{i18n("login.guest.alregister")}}</a>
              </div>
            </div>
            <div v-if="page === 2">
              <form novalidate enctype="multipart/form-data" class="inputBox">
                Carte d'identité :
              </form>
              <button @click="page++">{{i18n("login.guest.nextpage")}}</button>
            </div>
            <div v-if="page === 3">
              <p>
                Vous avez séléctionné un cursus qui possède des prérequis veuillez ajouter vos formations antérieures
                dans l'enseignement supérieur, votre dossier sera vérifié par un membre du service d'inscription.
              </p>
              <button @click="page++">Ajouter une formation</button>
              <button @click="postRegisterReq();">Envoyer la demande d'inscription</button>
            </div>
            <div v-if="page===4">
              <form @submit.prevent=""class="form">
                <div class="inputBox">
                  <p>Ecole</p>
                  <input type="text" v-model="externalCurr.school">
                </div>
                <div class="inputBox">
                  <p>Formation</p>
                  <input type="text" v-model="externalCurr.formation">
                </div>
                <div class="inputBox">
                  <p>Cochez la case si vous n'avez terminé cette formation</p>
                  <input v-model="notcompletedCheck" type="checkbox" id="checkboxformation">
                  <div v-if="notcompletedCheck">
                    <p>En quelle année de la formation vous êtes vous arrété (exemple: 3ème) ?</p>
                    <input type="text" v-model="externalCurr.completion">
                  </div>
                </div>
                <div class="inputBox">
                  <p>Année de début</p>
                  <input type="text" v-model="externalCurr.startYear">
                </div>
                <div class="inputBox">
                  <p>Année de fin</p>
                  <input type="text" v-model="externalCurr.endYear">
                </div>
                <div class="inputBox" style="margin-bottom:35px;">
                  <input type="submit" v-model="submitValue" @click="externalCurrTab.push({inscriptionReqId:null, school:externalCurr.school, formation:externalCurr.formation, completion:externalCurr.completion, startYear:externalCurr.startYear, endYear:externalCurr.endYear, justifdocUrl:externalCurr.justifdocUrl});console.log(externalCurrTab);page--;">
                </div>
              </form>
            </div>
          </form>
         </div>
    </div>
  </div>
  <div style="display:flex; justify-content:center; " v-for="item in externalCurrTab" v-if="page===3">
    <div class="bodu">
      <div class="container">
        <div class="school"><a style="margin-left:30px;">{{item.school}}</a></div>
        <div class="formation"><a>{{item.formation}}</a></div>
        <div class="edit">
          <button style="background-color:rgb(105,05,105);font-size:15px;height:50px;width:75%;border:none;border-radius:20px;" @click="externalCurr.school=item.school; externalCurr.completion=item.completion; externalCurr.formation=item.formation;externalCurr.endYear=item.endYear; externalCurr.startYear=item.startYear; externalCurr.justifdocUrl;page++;">Edit </button>
        </div>
        <div class="remove">
          <button style="background-color:rgb(105,05,105);font-size:15px;height:50px;width:75%;border:none;border-radius:20px;" @click="deleteExtCursus(item)">Remove </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

.setup {
  margin-left: auto;
  margin-right:auto;
  min-width:400px;
  width:25%;
  height:50%;
}


.loginBox {
  background-color: rgb(24,24,24);
  width: 400px;
  display:flex;
  justify-content: center;
  border-radius: 5%;
  box-shadow:0 5px 25px #000000;
}
.form {
  position:relative;
  width:100%;
  display: flex;
  flex-direction: column;
  align-items:center;
  gap: 3%;
}


.inputBox input,button,select {
  
  width:100%;
  border: none;
  margin-right: 12.5%;
  padding-left: 2.5%;
  padding-top:2.5%;
  padding-bottom:2.5%;
  outline:none;
  border-radius: 10px;
  font-size:1.35em;
}

.inputBox p{
  position:relative;
  z-index: 100;
  font-family:sans-serif ; 
  color:rgb(239,60,168);
  transition: 0.5;

}

.register{
  color:rgb(239,60,168);
  width:70%;
  margin-bottom:20px;
  margin-top:20px;
  cursor: pointer;
}

.bodu {
  margin-top:2%;
  width:50%;
  border:2px solid black;
  border-radius:9px;
  background-color:rgb(50,50,50);
}

.switchpage{
  width:100px;
  border: none;
  padding-right:0;
  padding-top:10px;
  padding-bottom:10px;
  outline:none;
  border-radius: 4px;
  font-size:0.8em;
  align-self: right;

}

input[type=submit],button,select{
  margin-bottom:20px;
  background-color: rgb(239,60,168);
  cursor: pointer;
  padding:10px;
  font-size:1.35em;
  border:none;
  border-radius:20px;

}

input[type=file]{
  display:none;
}

.browser{
  display:inline-block;
  cursor:pointer;
  border-radius:20px;
  background-color:rgb(239,60,168);
  padding:5%;
  font-size:1.35em;
  font-family:sans-serif;
  background:#FFFFFF;
}

.container{
  margin-top: 2%;
  color:white;
  height:60px;
  font-size:30px;
  display:grid;
  grid-template-columns:30% 30% 20% 20%;
  grid-template-areas:
    "school formation completion edit remove";
  column-gap:10px;
}

button:active ,.switchpage:active{
  opacity:0.8;

}


</style>
