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

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

      const response = await context.$dataProvider.invoke(
        {
          type: QUERY_TYPE.FILE,
          fileArgs: { fileId: file.value.id }
        } as DataProviderArgs
      )

      const blob = new Blob([response.data], { type: response.data.type })

      const url = window.URL.createObjectURL(blob)

      const link = document.createElement('a')
      link.href = url
      link.download = file.value.name ?? 'unknown'
      link.target = '_blank'
      link.click()

      link.remove()
      window.URL.revokeObjectURL(url)
    }

    return {
      submit,
      pending,
      file,
      download: () => download()
    }
  },
  beforeDestroy() {
    repositoryHelper.cleanRepository(File)
  }
})

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