<template>
  <div class="annotation-header">
    <h2 class="annotation-title">{{ $t('leftPanel.annotations') }}</h2>
    <div class="annotation-header-buttons">
      <Button
        className="button-icon"
        img="icon-import"
        :onClick="onExport"
        :title="$t('leftPanel.exportAnnotations')"
        :disabled="!annotations || annotations.annotationsCount === 0"
      ><Import /></Button>
      <Button
        className="button-icon"
        img="icon-export"
        :onClick="onImport"
        :title="$t('leftPanel.importAnnotations')"
        :disabled="totalPages <= 0"
      ><Export /></Button>
      <!-- <Button
        className="button-icon"
        img="icon-delete"
        :onClick="deleteAll"
        title="Delete"
      ></Button> -->
    </div>
  </div>
</template>

<script setup>
  import core from '@/core'
  import { computed, ref } from 'vue';
  import { useDocumentStore } from '@/stores/modules/document'
  import { useViewerStore } from '@/stores/modules/viewer'
  import { uploadFile } from '@/helpers/utils'
  import { isIOS } from '@/helpers/device'

  const useDocument = useDocumentStore()
  const useViewer = useViewerStore()
  const { removeAllAnnotations, importAnnotations, exportXfdf } = core
  
  const onImport = () => {
    const type = isIOS ? '' : '.xfdf'
    uploadFile(type).then((file) => {
      const extension = file.name.split('.').pop().toLowerCase()
      if (extension !== 'xfdf') return
      importAnnotations(file)
    })
  }

  const totalPages = computed(() => useDocument.getTotalPages)
  const annotations = computed(() => useDocument.getAllAnnotations)
  const optionUrl = computed(() => useDocument.getOptionUrl)
  const info = computed(() => useDocument.info)
  const fileName = info.value && info.value.token && atob(info.value.token).replace('.pdf', '.xfdf');
  const fetchWithBlob = (uri) =>
    fetch(uri, {
      responseType: 'blob',
    }).then((res) => {
      if (!res.ok) {
        return Promise.reject({
          status: res.status,
          message: res.statusText
        })
      }
      return res.blob()
    }).catch((error) => {
      return Promise.reject({ error: true, message: error.message })
    });

  const onExport = async () => {
    // if (annotationsCount.value < 1) return
    // const outputPath = `${optionUrl.value.baseUrl}${optionUrl.value.getAnnotations}?f=${info.value.token}`
    // fetchWithBlob(outputPath)
    // .then(data => {
    //   const blob = new Blob([data], { type: "application/vnd.adobe.xfdf" });
    //   downloadFileWithUri(fileName, outputPath, blob);
    // })
    try {
      useViewer.setDownloading(true)
      const res = await exportXfdf(true)
      useViewer.setDownloading(false)
      if (!res) {
        useViewer.setDownloadError('Downloaded')
      }
    } catch (error) {
      console.log(error)
      useViewer.setDownloading(false)
      useViewer.setDownloadError('Downloaded')
    }
  }


const downloadFileWithUri = (name, uri, blob) => {
  if (!blob) {
    // URL.createObjectURL is not supported
    download(uri, name);
    return;
  }
  const blobUrl = URL.createObjectURL(blob);
  download(blobUrl, name);
};

function download(blobUrl, filename) {
  const a = document.createElement("a");
  if (!a.click) {
    throw new Error('DownloadManager: "a.click()" is not supported.');
  }
  a.href = blobUrl;
  a.target = "_blank";
  // Use a.download if available. This increases the likelihood that
  // the file is downloaded instead of opened by another PDF plugin.
  if ("download" in a) {
    a.download = filename;
  }
  // <a> must be in the document for recent Firefox versions,
  // otherwise .click() is ignored.
  (document.body || document.documentElement).appendChild(a);
  a.click();
  a.remove();
}

  const deleteAll = () => {
    removeAllAnnotations()
  }
</script>

<style lang="scss">
  .annotation-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 16px;

    .annotation-title {
      padding: 0;
    }

    .annotation-header-buttons {
      display: flex;
      align-items: center;

      button {
        padding: 0;
        margin-right: 0;

        & + button {
          margin-left: 8px;
        }
      }
    }
  }
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
</style>
