<template>
  <c-header title="BDLG Inscription Benevole" />
  <div style="display: flex; justify-content: center">
    <dots v-if="status == 'Loading'" />
    <h2 v-if="status.startsWith('Error')">{{ status }}</h2>
    <div v-if="status == 'Loaded'" class="inscription-container">
      <questionnaire
        :competences="competences"
        :introduction="introduction"
        :questions="questions"
        :uuid="uuid"
        :evtName="evtName"
        :emailList="emailList"
      />
    </div>
  </div>
  <c-footer />
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { validate as validateUuid } from "uuid";
import cHeader from "@/components/Header.vue";
import cFooter from "@/components/Footer.vue";
import Questionnaire from "@/components/Questionaire.vue";
import dots from "@/components/Dots.vue";

import { StateJSON } from "@/store/State";
import Benevole, { BenevoleJSON } from "@/models/Benevole";
import Competence from "@/models/Competence";
import getQuestionnaire from "./mixins/getQuestionnaire";

const API_URL = process.env.VUE_APP_API_URL;

export default defineComponent({
  components: { cHeader, cFooter, dots, Questionnaire },
  mixins: [getQuestionnaire],
  data() {
    return {
      uuid: location.pathname.split("/").pop(),
      status: "Loading",
      data: null as StateJSON | null,
      registration: [] as Array<Benevole>,
      competences: [] as Array<Competence>,
    };
  },
  computed: {
    evtName(): string {
      return this.data?.evenement.name ?? "";
    },
    emailList(): Array<string> {
      return this.registration.map((b) => b.email);
    },
  },
  methods: {
    addBenevoles(data: Array<BenevoleJSON>) {
      this.registration.push(...data.map((o) => Benevole.fromJSON(o)));
    },
  },
  mounted() {
    // Get event data
    const uuid = this.uuid;
    if (uuid && validateUuid(uuid)) {
      this.getQuestionnaire(uuid);
      fetch(`${API_URL}api/evenements/${uuid}`)
        .then((res) => {
          if (res.status == 200) {
            this.status = "Loaded";
            return res.json();
          } else {
            this.status = "Error 404";
            throw new Error(res.statusText);
          }
        })
        .then((data: StateJSON) => {
          this.data = data;
          this.competences = data.competences.map((o) => Competence.fromJSON(o));
          this.addBenevoles(data.benevoles);
        });
      // Get existing registration
      fetch(`${API_URL}api/inscription/${uuid}`)
        .then((res) => {
          if (res.status == 200) {
            return res.json();
          } else {
            throw new Error(res.statusText);
          }
        })
        .then((data: Array<BenevoleJSON>) => this.addBenevoles(data));
    } else {
      this.status = "Error 404";
    }
  },
});
</script>

<style scoped>
.inscription-container {
  max-width: 600px;
  padding: 8px;
}
</style>
