<template>
  <a :class="props.classes" @click="download_and_open($event)" ref="btn">
    <i class="fa fa-file-pdf-o"></i>
    Télécharger en pdf
  </a>
</template>

<script lang="ts" setup>
import {
  build_convert_link,
  download_and_decrypt_doc,
  download_doc,
} from "./helpers";
import mime from "mime";
import { reactive, ref } from "vue";
import { StoredObject } from "../../types";

interface ConvertButtonConfig {
  storedObject: StoredObject;
  classes: Record<string, boolean>;
  filename?: string;
}

interface DownloadButtonState {
  content: null | string;
}

const props = defineProps<ConvertButtonConfig>();
const state: DownloadButtonState = reactive({ content: null });
const btn = ref<HTMLAnchorElement | null>(null);

async function download_and_open(event: Event): Promise<void> {
  const button = event.target as HTMLAnchorElement;

  if (null === state.content) {
    event.preventDefault();

    const raw = await download_doc(build_convert_link(props.storedObject.uuid));
    state.content = window.URL.createObjectURL(raw);

    button.href = window.URL.createObjectURL(raw);
    button.type = "application/pdf";

    button.download = props.filename + ".pdf" || "document.pdf";
  }

  button.click();
  const reset_pending = setTimeout(reset_state, 45000);
}

function reset_state(): void {
  state.content = null;
  btn.value?.removeAttribute("download");
  btn.value?.removeAttribute("href");
  btn.value?.removeAttribute("type");
}
</script>

<style scoped lang="scss">
i.fa::before {
  color: var(--bs-dropdown-link-hover-color);
}
</style>
