<template>
  <div class="d-flex flex-column align-center">
    <h2 class="ma-4">{{ $t('cmf_structure_licence')}}</h2>
    <a
        href="https://www.cmf-musique.org/services/tarifs-preferentiels/"
        target="_blank"
    >
      {{ $t('cmf_licence_details_url')}}
    </a>

    <v-form
        ref="form"
        lazy-validation
    >
      <div class="ma-12">
        <v-btn
            v-if="!pending && file === null"
            @click="submit"
        >
          {{ $t('generate') }}
        </v-btn>

        <v-btn
            v-else
            color="primary"
            :loading="pending"
            :disabled="pending"
            target="_blank"
            @click="download"
        >
          {{ $t('download') }}
        </v-btn>
      </div>
    </v-form>
  </div>
</template>

<script setup lang="ts">
import File from "~/models/Core/File"
import {ComputedRef, Ref} from "vue";
import {useEntityFetch} from "~/composables/data/useEntityFetch";
import {useSseStore} from "~/stores/sse";
import {useEntityManager} from "~/composables/data/useEntityManager";
import LicenceCmfOrganizationER from "~/models/Export/LicenceCmfOrganizationER";
import {useDownloadFile} from "~/composables/utils/useDownloadFile";
import {useRepo} from "pinia-orm";

const { em } = useEntityManager()
const { getRef } = useEntityFetch()

const sseStore = useSseStore()
const async = () => { return sseStore.connected }

const fileId = ref(null)

// TODO: il y a quelque chose à creuser ici, cette ref est nécessaire pour garder le lien avec le store,
//       car on ne peut pas directement passer par le fetch de useEntityFetch ici (puisqu'on a pas encore l'id
//       au chargement). Il faudrait voir si on ne pourrait pas intégrer ça au fetch, ou faire un fetchOrNull, qui
//       combine fetch et getRef?
const file: ComputedRef<File | null> = getRef(File, fileId)

// Submitting export request
const submitting: Ref<boolean> = ref(false)

// File is downloading
const downloading: Ref<boolean> = ref(false)

const pending: ComputedRef<boolean> = computed(() => {
  return submitting.value || (file.value !== null && file.value.status === 'PENDING') || downloading.value
})

const submit = async () => {
  submitting.value = true

  const exportRequest = em.newInstance(LicenceCmfOrganizationER)

  exportRequest.format = 'pdf'

  if (async()) {
    exportRequest.async = true
  } else {
    console.error('SSE unavailable - File will be downloaded synchronously')
  }

  try {
    // Send the export request and get the receipt
    const receipt = await em.persist(LicenceCmfOrganizationER, exportRequest)
    if (receipt.fileId === null) {
      throw new Error("Missing file's id, abort")
    }
    fileId.value = receipt.fileId

    // Fetch the newly created file from API. If export is async, it will be a record about a pending file,
    // SSE will update its status to ready when it'll be.
    await em.fetch(File, receipt.fileId)

  } finally {
    submitting.value = false
  }
}

const download = async () => {
  downloading.value = true

  if (file.value === null) {
    console.error("File is not defined yet, impossible to download")
    return
  }

  if (file.value.status === 'PENDING') {
    console.error("File is still pending, impossible to download")
    return
  }

  try {
    await useDownloadFile(file.value)
  } finally {
    downloading.value = false
  }
}
</script>
