<template>
  <v-btn :disabled="true" variant="outlined" @click="onClick">
    {{$t('download_pdf')}}
  </v-btn>
</template>

<script setup lang="ts">
import { target } from '@vue/devtools-shared'

const appStore = useAppStore()

const onClick = async () => {
  // if (appStore.altchaPayload) {
    await submit()
  // } else {
  //   console.log('missing payload')
  // }
}

const submit = async () => {
  const url = 'https://api.ogene.fr/api/download-cv';
  const headers = {
    'Content-Type': 'application/ld+json'
  };
  const body = {
    "altchaPayload": appStore.altchaPayload
  };

  // try {
    const response = await fetch(url, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body)
    });

    const base64 = await toBase64(await response.text())
    const binary = atob(base64.split(',')[1]);

    const array = [];
    for (let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }

    // Create a blob object
    const blob = new Blob([new Uint8Array(array)], { type: 'application/pdf' });

    const blobUrl = URL.createObjectURL(blob);

    window.open(blobUrl, '_blank');
  // } catch (error) {
  //   console.error('There was a problem with the fetch operation: ', error);
  // }
}

const newBlob = (data: BlobPart, filetype: string = 'image/jpeg'): Blob => {
  return new Blob([data], { type: filetype })
}

const blobToBase64 = async (blob: Blob): Promise<string> => {
  return new Promise((resolve, _reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result as string)
    reader.readAsDataURL(blob)
  })
}

const toBase64 = async (data: BlobPart) => {
  const blob = newBlob(data)
  return (await blobToBase64(blob)) ?? ''
}
</script>

<style scoped lang="scss">

</style>