<template>
  <div id="findbar" class="findbar">
    <div id="findbarInputContainer" class="findbar-input-container">
      <div class="input-container">
        <input id="findInput" class="toolbarField" title="Find" placeholder="Find in document…">
        <EmptyInput id="emptyInput" class="empty-input hidden" />
      </div>
      <div class="button-container">
        <Button
          img="icon-previous-left"
          id="findPrevious"
          class="toolbarButton disabled"
          title="Find the previous occurrence of the phrase"
        ><ArrowPrev />
        </Button>
        <Button
          img="icon-next-right"
          id="findNext"
          class="toolbarButton disabled"
          title="Find the next occurrence of the phrase"
        ><ArrowNext />
        </Button>
      </div>
    </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'
 
  const useDocument = useDocumentStore()
  const useViewer = useViewerStore()
  const { removeAllAnnotations, importAnnotations, exportAnnotations } = core
  const onImport = () => {
    
    uploadFile('.xfdf').then((data) => {
      importAnnotations(data)
    })
  }

  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 exportAnnotations()
      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">
  .findbar {
    padding: 8px 0 8px 8px;
    .findbar-input-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .input-container {
      position: relative;
      flex-grow: 1;
      display: flex;
      width: 180px;
      padding: 0 8px;
      border-radius: 1px;
      border: 1px solid var(--c-findbar-input-border);
      background-color: var(--c-findbar-input-bg);
    }
    input {
      flex-grow: 1;
      width: 0;
      height: 30px;
      outline: none;
      padding: 5px 8px;
      box-shadow: none;
      border: none;
      background-color: var(--c-findbar-input-bg);
      color: var(--c-findbar-text);
      font-size: 16px;
    }
    .empty-input {
      position: absolute;
      right: 4px;
      top: 7px;
      cursor: pointer;
    }
    .toolbarLabel {
      font-size: 14px;
      line-height: 30px;
      color: var(--c-findbar-text);
      white-space: nowrap;
    }
    .button-container {
      display: flex;
      align-items: center;
      button {
        margin-left: 8px;
        padding: 0;
        color: var(--c-findbar-text);
      }
    }
  }
</style>
