<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 && fileUrl === null"
          @click="submit"
        >
          {{ $t('generate') }}
        </v-btn>

        <v-btn
          v-else
          color="primary"
          :loading="pending"
          :disabled="pending"
          :href="fileUrl">
          {{ $t('download') }}
        </v-btn>
      </div>
    </v-form>
    <!-- <<< for debugging purposes, TODO: remove before deploying -->
    <ul>
      <li v-for="event in events">{{ event }}</li>
    </ul>
    <!-- >>> for debugging purposes -->
  </div>
</template>

<script lang="ts">
import {defineComponent, Ref, ref, useContext} from "@nuxtjs/composition-api";
import {HTTP_METHOD, QUERY_TYPE} from "~/types/enums";
import DataPersister from "~/services/data/dataPersister";
import {DataPersisterArgs} from "~/types/interfaces";

export default defineComponent({
  name: 'OrganizationCmfLicence',
  setup() {
    const { store } = useContext()

    let pending: Ref<boolean> = ref(false)
    let fileUrl: Ref<string | null> = ref(null)

    const async = () => { return store.state.sse.connected }

    let events: Ref<Array<Array<any>>> = ref(store.state.sse.events)

    const submit = async () => {
      const response = await DataPersister.request(
        '/api/export/cmf-licence/organization',
        HTTP_METHOD.POST,
        { type: QUERY_TYPE.DEFAULT, data: { format: 'pdf', async: true }, withCredentials: true } as DataPersisterArgs
      )
      if (async()) {
        pending.value = true
      } else {
        console.warn('File downloaded synchronously')
        fileUrl.value = JSON.parse(response).url
      }
    }

    // const onMessage = (eventData) => {
    //   fileUrl.value = eventData.url
    //   pending.value = false
    // }

    return {
      submit,
      pending,
      fileUrl,
      events
    }
  }
})

function useSse(): { sseConnected: any; } {
    throw new Error("Function not implemented.");
}
</script>
