<script setup>
import data from "@/data.json";

import { ref, computed } from "vue";

import { useStore } from "@/stores";

import { Splide, SplideSlide } from "@splidejs/vue-splide";
import Question from "./Question.vue";
import "@splidejs/splide/dist/css/splide.min.css";
import ScoreHeader from "./ScoreHeader.vue";
import { toPng } from "html-to-image";

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
});

const score = data.find((score) => score.id == props.id);
const slides = ref();

const store = useStore();
const language = store.language;

function formatAnswers(answers) {
  return answers
    .map((answer) => answer.answers_id)
    .map((answer) => {
      const translation = answer.translations.filter(
        (item) => item.languages_code == language
      );
      return {
        id: answer.id,
        title: translation.length > 0 ? translation[0].title : answer.title,
        weight: answer.weight,
        image: answer.image,
      };
    });
}

function formatScore(score) {
  return score.questions
    .map((question) => question.questions_id)
    .map((question) => {
      const translation = question.translations.filter(
        (item) => item.languages_code == language
      );
      const answers = formatAnswers(question.answers);
      return {
        id: question.id,
        weight: answers[0].weight,
        title: translation.length > 0 ? translation[0].title : question.title,
        function: question.function,
        answers: answers,
        splide: ref(),
      };
    });
}
function getTranslation(translations, key) {
  return translations.find((translation) => translation[key] == store.language);
}
const title = score ? getTranslation(score.translations, "languages_id").title : "";
const questions = ref(formatScore(score));

const scoreSum = computed(() => {
  return questions.value
    .map((question) => question.weight)
    .reduce((value, currentValue) => value + currentValue, 0);
});
const displayScoreResult = computed(
  () => !questions.value.filter((q) => q.weight == null).length
);
function getResultsFromScore(score) {
  return score.results
    .map((result) => result.results_id)
    .map((result) => {
      const translation = result.translations.filter(
        (item) => item.languages_code == language
      );
      return {
        id: result.id,
        max: result.max,
        min: result.min,
        pde_qtra: result.pde_qtra,
        effets: translation.length > 0 ? translation[0].effets : "",
        facteur: translation.length > 0 ? translation[0].facteur : "",
        pde: translation.length > 0 ? translation[0].pde : "",
      };
    });
}
const results = ref(getResultsFromScore(score));
const result = computed(() =>
  displayScoreResult.value
    ? results.value
        .filter((r) => !r.min || r.min <= scoreSum.value)
        .filter((r) => !r.max || r.max >= scoreSum.value)[0]
    : null
);
function goQuestionSlide(question) {
  console.log(slides.value);
  slides.value.go(
    questions.value.findIndex((element) => element.id === question.id)
  );
}
function answerSelected(question, answerWeight) {
  questions.value.find((q) => q.id === question.id).weight = answerWeight;
}

function nextQuestion() {
  setTimeout(() => {
    slides.value.go(">");
    console.log(slides);
  }, 100);
}

const saveAs = (blob, fileName) => {
  var elem = window.document.createElement("a");
  elem.href = blob;
  elem.download = fileName;
  elem.style = "display:none;";
  (document.body || document.documentElement).appendChild(elem);
  if (typeof elem.click === "function") {
    elem.click();
  } else {
    elem.target = "_blank";
    elem.dispatchEvent(
      new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true,
      })
    );
  }
  URL.revokeObjectURL(elem.href);
  elem.remove();
};

const sharing = ref(false);
async function share() {
  sharing.value = true;
  const filter = (node) => {
    const exclusionClasses = ["btn"];
    return !exclusionClasses.some((classname) =>
      node.classList?.contains(classname)
    );
  };
  const body = document.querySelector("body");
  body.classList.add("print");
  const dataUrl = await toPng(body, { filter: filter });
  body.classList.remove("print");
  const fileName = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replaceAll(':', '-')
  saveAs(dataUrl, `Ceiba-score-${fileName}.png`);
  sharing.value = false;
}
</script>

<template>
  <ScoreHeader v-if="title" :title="title" />
  <Splide
    ref="slides"
    class="questions"
    v-if="questions"
    :options="{
      pagination: false,
      speed: 700,
      height: '100%',
      arrows: false,
      direction: 'ttb',
      wheel: true,
      releaseWheel: true,
    }"
  >
    <SplideSlide v-for="question in questions" :key="question.id">
      <Question
        :question="question"
        @answerSelected="answerSelected"
        @nextQuestion="nextQuestion"
      />
    </SplideSlide>
    <SplideSlide class="latest">
      <template v-if="displayScoreResult && result">
        <div>
          <h2 class="center">Probabilité d'échec</h2>
          <h2 class="center">{{ result.pde_qtra }}</h2>
          <div class="gradient">
            <div
              v-for="(item, index) in [...Array(7).keys()]"
              :class="{ active: result && result.pde_qtra === index + 1 }"
              :key="item"
            >
              {{ index + 1 }}
            </div>
          </div>
          <div class="details">
            <p>Rappel des paramètres choisis :</p>
            <ul>
              <li v-for="question in questions" :key="question.id">
                {{ question.title }} :
                {{
                  question.answers.find(
                    (answer) => answer.weight === question.weight
                  ).title
                }}
              </li>
            </ul>
          </div>
          <button class="btn download" @click="() => share()" v-if="!sharing">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36">
              <path
                fill="#D99E82"
                d="M36 32c0 2.209-1.791 4-4 4H4c-2.209 0-4-1.791-4-4v-9c0-2.209.791-3 3-3h30c2.209 0 3 .791 3 3v9z"
              />
              <path
                fill="#662113"
                d="M25 20c0 3.866-3.134 7-7 7s-7-3.134-7-7h14z"
              />
              <path
                fill="#C1694F"
                d="M4 36h28c2.209 0 4-1.791 4-4H0c0 2.209 1.791 4 4 4z"
              />
              <path
                fill="#77B255"
                d="M26.716 8h-4.783V2c0-1.105-.896-2-2-2h-4.001c-1.104 0-1.999.896-1.999 2v6H9.148c-1.223 0-1.516.623-.651 1.489l7.863 7.863c.865.865 2.28.865 3.146 0l7.863-7.863C28.232 8.623 27.94 8 26.716 8z"
              />
            </svg>
          </button>
          <button class="btn spin" v-if="sharing">
            <img src="/spin.svg" />
          </button>
        </div>
      </template>
      <template v-else>
        <div class="noscore">
          <p>
            Aucun score ne peut vous être proposé, vous devez faire une
            sélection sur les paramètres suivants :
          </p>
          <ul>
            <li
              v-for="question in questions.filter((q) => q.weight == null)"
              :key="question.id"
            >
              <a
                @click="
                  (event) => {
                    goQuestionSlide(question);
                    return false;
                  }
                "
                href="javascript:;"
                >{{ question.title }}</a
              >
            </li>
          </ul>
        </div>
      </template>
    </SplideSlide>
  </Splide>
</template>

<style lang="sass" scoped>
.spin
  bottom: 1.5rem
  right: 1.5rem
  img
    position: absolute
    top: 50%
    left: 50%
    width: 30px
    height: 30px
    margin: -15px 0 0 -15px
    -webkit-animation: spin 2s linear infinite
    -moz-animation: spin 2s linear infinite
    animation: spin 2s linear infinite

@-moz-keyframes spin
  100%
    -moz-transform: rotate(360deg)

@-webkit-keyframes spin
    100%
      -webkit-transform: rotate(360deg)

@keyframes spin
  100%
    -webkit-transform: rotate(360deg)
    transform: rotate(360deg)


.center
  text-align: center
.download
  bottom: 1.5rem
  right: 1.5rem
  opacity: .7
.noscore
  display: flex
  justify-content: center
  align-items: center
  height: 100%
  color: var(--color-text)
  flex-direction: column

  p
    font-size: 1rem
    text-align: center
    margin-bottom: 1rem
  a
    color: var(--color-text)
.questions
  position: fixed
  top: var(--header-size)
  left: 0
  right: 0
  bottom: 0
  background: transparent


.splide__slide
  position: relative
  padding: 1rem

.splide__track
  overflow: visible!important

legend
  font-size: 1.1rem
  font-weight: bold

label
  display: inline-block
  width: 100%
  padding: .3rem

.latest
  background-color: var(--color-highlight-background)
  color: var(--color-highlight-text)
  display: flex
  align-items: center
  justify-content: center

  h2
    font-size: 2rem
    font-weight: bold
    & + h2
      line-height: 2rem
      font-size: 2.6rem

    @media (max-height: 600px)
      font-size: 1.5rem
      & + h2
        font-size: 2rem

  ul
    text-align: left
    padding-left: 1.5rem
    list-style-type: disc

  .details
    text-align: left !important
    font-family: serif
    font-size: .9rem
    line-height: normal
    background: var(--color-highlight-background)
    border: 1px solid var(--color-highlight-text)
    padding: 1rem

.gradient
  padding: 0 1rem
  height: 3rem
  background-image: linear-gradient(to right, red, red, rgb(255, 255, 0), rgb(255, 255, 0), green, green)
  display: flex
  margin: 2.5rem auto
  align-items: center
  border-radius: 3px
  max-width: 30rem
  text-shadow: 1px 1px 4px var(--color-highlight-text-invert),-1px -1px 4px var(--color-highlight-text-invert), -1px 1px 4px var(--color-highlight-text-invert), 1px -1px 4px var(--color-highlight-text-invert)
  color: var(--color-highlight-text)

  div
    width: calc(100%/7)
    text-align: center
    align-self: center
    font-weight: bold

  .active
    position: relative

    &:before
      content: ""
      border: 1px solid var(--color-highlight-text)
      border-radius: 3px
      top: -2.8rem
      bottom: -1.5rem
      position: absolute
      width: 100%
      font-weight: bold
      display: flex
      align-items: center
      justify-content: center

    &::after
      content: "PdE"
      position: absolute
      font-size: 1rem
      top: -2rem
      bottom: -1.5rem
      left: 0
      right: 0
      line-height: .7rem
      text-shadow: none

.splide__arrows
  position: inherit
</style>
