<script setup>
import {onMounted, ref} from 'vue';
import {useErrorStore} from '@/stores/errors'
import Loader from '@/components/Loader.vue';
import {useRoute} from 'vue-router';
import {useAuthStore} from '@/stores/auth';
import {storeToRefs} from 'pinia';
import router from '@/router';

const errorStore = useErrorStore();
const authStore = useAuthStore();
const { auth } = storeToRefs(authStore);
const apiHost = import.meta.env.VITE_CONJUREOS_HOST;

const route = useRoute();
const gameId = ref(route.params.gameId);
const game = ref(undefined);
const isActivating = ref(false);
const confirmingDeletion = ref(false);

onMounted(() => {
  fetch(apiHost + 'games/' + gameId.value, {
    method: 'GET',
    headers: { 'API-Version': 1 },
  })
    .then((response) => response.json())
    .then((result) => {
      game.value = result;
    })
    .catch((error) => {
      console.error('Error:', error);
      errorStore.unshift(error);
    });
});

function tryDeleteGame() {
  console.log("Try")
  confirmingDeletion.value = true;
  new Promise((_) => setTimeout(_, 1000)).then(() => {
    confirmingDeletion.value = false;
  });
}

function deleteGame() {
  console.log("Delete")
  fetch(`${apiHost}games/${gameId.value}`, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${auth.value.token}`,
      'API-Version': 1,
    },
  })
    .then((response) => {
      if (response.ok) {
        alert("Deleted")
        router.back()
      }
      else {
        alert("Error deleting game")
      }
      return true;
    })
    .catch((error) => {
      errorStore.unshift(error);
    });
}

function toggleActivation(state) {
  isActivating.value = true;
  fetch(`${apiHost}games/${gameId.value}/${state ? 'activate' : 'deactivate'}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${auth.value.token}`,
      'API-Version': 1,
    },
  })
    .then((response) => {
      if (response.status !== 204) return response.json().then((errorBody) => { throw new Error(errorBody); });
      return true;
    })
    .then(() => {
      game.value = { ...game.value, active: state };
      isActivating.value = false;
    })
    .catch((error) => {
      errorStore.unshift(error);
      isActivating.value = false;
    });
}

</script>

<template>
  <article>
    <loader v-if="game === undefined"></loader>
    <div v-else>
      <img v-if="game.image" :src="'data:image/png;base64,'+game.image" alt="thumbnail"/>
      <h1>{{ game.game }}</h1>
      <p>{{ game.description }}</p>
      <loader :variant="2" v-if="isActivating"></loader>
      <template v-else>
        <button
          :class="game.active ? 'bg-red-500 text-white hover:bg-red-700' : 'bg-green-500 text-white hover:bg-green-700'"
          class="font-bold py-2 px-4 my-2 rounded"
          @click="toggleActivation(!game.active)"
          :disabled="isActivating"
        >
          {{ game.active ? 'Deactivate' : 'Activate' }}
        </button>

        <button
        class="font-bold py-2 px-4 m-2 rounded bg-red-500 text-white hover:bg-red-700"
        @click="confirmingDeletion ? deleteGame() : tryDeleteGame()"
        >
          {{ confirmingDeletion ? "Sure?" : "Delete" }}
        </button>
      </template>
    </div>
  </article>
</template>

<style scoped lang="scss">

article {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

</style>