<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>

        <UiDownloader v-else :file="file" v-slot="scope">
          <v-btn
            color="primary"
            :loading="pending || scope.downloading"
            :disabled="pending"
            @click="scope.download"
          >
            {{ $t('download') }}
          </v-btn>
        </UiDownloader>

      </div>
    </v-form>
  </div>
</template>

<script lang="ts">
import {computed, ComputedRef, defineComponent, Ref, ref, useContext} from "@nuxtjs/composition-api";
import {QUERY_TYPE} from "~/types/enums";
import DataPersister from "~/services/data/dataPersister";
import {DataPersisterArgs, DataProviderArgs} from "~/types/interfaces";
import { Context } from "@nuxt/types";
import {Repository as VuexRepository} from "@vuex-orm/core/dist/src/repository/Repository";
import {Model, Query} from "@vuex-orm/core";
import {repositoryHelper} from "~/services/store/repository";
import {File} from "~/models/Core/File";
import {queryHelper} from "~/services/store/query";
import DataProvider from "~/services/data/dataProvider";

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

    let fileId: Ref<number | null> = ref(null)

    let file: ComputedRef<File | null> = computed(() => {
      return fileId.value !== null ? queryHelper.getItem(query, fileId.value) as File : null
    })

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

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

    const repository: VuexRepository<Model> = repositoryHelper.getRepository(File)
    const query: Query = repository.query()

    const submit = async () => {
      const response = await context.$dataPersister.invoke(
        {
          url: '/api/export/cmf-licence/organization',
          type: QUERY_TYPE.DEFAULT,
          data: { format: 'pdf', async: async() },
          withCredentials: true
        } as DataPersisterArgs
      )

      if (!async()) {
        console.error('SSE unavailable - File downloaded synchronously')
      }

      fileId.value = response.data.id
      repositoryHelper.persist(File, response.data)
    }

    return {
      submit,
      pending,
      file
    }
  },
  beforeDestroy() {
    repositoryHelper.cleanRepository(File)
  }
})

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