<template>
  <div class="k-number-field k-field k-field-name-mapadoid">
    <k-button variant="filled" :theme="theme" :icon="icon" @click="connect"
      >Vérifier</k-button
    >
    <footer class="k-field-footer">
      <div class="k-help k-field-help k-text">
        <p v-html="text"></p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref } from "vue";

const { mapadoToken } = defineProps({
  mapadoToken: String,
});

const id = ref(null);

const icon = ref("search");
const theme = ref(null);
const text = ref("Vérifie si Mapado contient bien un événement correspondant.");

setTimeout(() => {
  const idInput = document.querySelector(".k-field-name-mapadoid input");

  id.value = idInput.value;

  idInput.addEventListener("input", () => {
    id.value = idInput.value;
  });
}, 100);

function connect() {
  icon.value = "loader";
  theme.value = "yellow";
  const myHeaders = new Headers();
  myHeaders.append("Authorization", "Bearer " + mapadoToken);

  const requestOptions = {
    method: "GET",
    headers: myHeaders,
    redirect: "follow",
  };

  fetch(
    "https://ticketing.mapado.net/v1/ticketings/" +
      id.value +
      "?fields=title,type,sellingDeviceSchedule,eventDateList{startDate,bookableStock}",
    requestOptions
  )
    .then((response) => {
      console.log(response);
      if (response.status === 404) {
        throw new Error(
          "Aucun événement ne correspond à l'identifiant : " + id.value + "."
        );
      }
      if (response.status === 500) {
        throw new Error(
          "Impossible de joindre le serveur Mapado. Veuillez réessayer plus tard."
        );
      }
      return response.json();
    })
    .then((result) => {
      icon.value = "check";
      theme.value = "green";
      text.value =
        "<strong>Événement correspondant sur Mapado : <em>" +
        result.title +
        "</em></strong>";
      console.log(result);
    })
    .catch((error) => {
      icon.value = "alert";
      theme.value = "red";
      text.value = "<strong>" + error + "</strong>";
      console.log(error);

      setTimeout(() => {
        icon.value = "search";
        theme.value = null;
      }, 2000);
    });
}
</script>

<style scoped>
button {
  margin-top: 2rem;
}
</style>
