<script lang="ts" setup>

import {type AxeResponses, type QuizResponse, useQuizStore} from "~/store/quiz";
import Quiz from "~/pages/quiz.vue";
import {type Axe, useAxeStore} from "~/store/axe";

const loading = ref(true);
const quiz = ref<Quiz>();
const axes = ref<Axe[]>();

onMounted(() => {
  if (!useRoute().query.quiz) {
    navigateTo("/dashboard");
  }
  loading.value = true;
  const quizId = Number.parseInt(useRoute().query.quiz as string);
  useQuizStore().findById(quizId)
    .then((result: Quiz) => {
      quiz.value = result;
    })
    .then(() => {
      useAxeStore().findAxes().then(result => {
        axes.value = result.filter(axe => {
          return quiz.value.axes.filter(axeResponse => axeResponse.axeIdentifier === axe.identifier).length > 0;
        });
      });
    })
    .finally(() => {
      loading.value = false;
    });
});

function getAverage(axe: Axe): number {
  const axeResponses = quiz.value.axes.filter((response: AxeResponses) => response.axeIdentifier === axe.identifier);
  if (axeResponses.length === 1) {
    return axeResponses[0].average;
  }
  return 0;
}

function getResponses(axe: Axe): QuizResponse[] {
  const axeResponses = quiz.value.axes.filter((response: AxeResponses) => response.axeIdentifier === axe.identifier);
  if (axeResponses.length === 1) {
    return axeResponses[0].responses;
  }
  return [];
}

function print() {
  window.print();
}
</script>
<template>
  <section v-if="!loading">
    <span class="date">{{ formatDateTime(quiz.createdDate) }}</span>
    <quiz-axe-details
      v-for="axe in axes"
      :axe="axe"
      :average="getAverage(axe)"
      :responses="getResponses(axe)"/>
  </section>
  <loader v-else class="center"/>
  <div class="button-container">
    <nuxt-link class="button gray button-back" to="/dashboard" aria-label="Retour à l'accueil">❮</nuxt-link>
    <button class="button orange button-print" @click="print">Imprimer</button>
  </div>
</template>


<style lang="scss" scoped>
section {
  margin: $small 0;
}

.date {
  font-weight: 700;
  font-size: $tertiary-font-size;
  color: $gray_4;
}

@media print {
  .button-container {
    display: none;
  }
}

</style>
