<template>
  <Dialog
    id="add-pdf"
    v-model:visible="isOpen"
    modal
    :draggable="false"
    dismissableMask="true"
    header="Titre du PDF"
    class="dialog"
    :class="{ 'with-comments': isCommentsOpen }"
    :closeOnEscape="true"
  >
    <template #header>
      <button
        v-if="
          dialog.content.id === 'clientBrief' &&
          dialog.content.isValidated !== true
        "
        class="btn"
        @click="validate()"
      >
        Valider et envoyer le brief
      </button>
      <h2
        v-if="openedFile"
        class="font-serif text-lg"
        :title="openedFile?.label.length ? openedFile.label : openedFile.name"
      >
        {{ openedFile?.label.length ? openedFile.label : openedFile.name }}
      </h2>
    </template>
    <div id="vpv-container">
      <PdfViewer />
    </div>
  </Dialog>
</template>

<script setup>
import Dialog from "primevue/dialog";
import PdfViewer from "./PdfViewer.vue";
import { ref, watch } from "vue";
import { useDialogStore } from "../../stores/dialog";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useApiStore } from "../../stores/api";

const { openedFile, isCommentsOpen } = storeToRefs(useDialogStore());

const router = useRouter();
const route = useRoute();

const dialog = useDialogStore();
const api = useApiStore();

const isOpen = ref(true);
watch(isOpen, (newValue) => {
  router.push({ name: route.name });
});

openedFile.value = route.query.fileIndex
  ? dialog.content.files[route.query.fileIndex]
  : dialog.content.files[0];

// Functions
async function validate() {
  const response = await api.validateBrief(
    route.path + "/client-brief",
    route.fullPath
  );
  if (response.success) {
    dialog.content.isValidated = true;
  } else {
    console.alert(response);
  }
}
</script>

<style>
#vpv-container {
  width: var(--dialog-max-w);
  height: calc(var(--dialog-max-h) - var(--dialog-header-h));
  background: black;
  position: relative;
}
.with-comments .vpv-pages-container-wrapper {
  margin-right: var(--dialog-comments-w, 20rem);
}
</style>
