<template>
  <a
    :class="Object.assign(props.classes, { btn: true })"
    @click="beforeLeave($event)"
    :href="build_wopi_editor_link(props.storedObject.uuid, props.returnPath)"
  >
    <i class="fa fa-paragraph"></i>
    Editer en ligne
  </a>
</template>

<script lang="ts" setup>
import WopiEditButton from "./WopiEditButton.vue";
import { build_wopi_editor_link } from "./helpers";
import {
  StoredObject,
  WopiEditButtonExecutableBeforeLeaveFunction,
} from "../../types";

interface WopiEditButtonConfig {
  storedObject: StoredObject;
  returnPath?: string;
  classes: Record<string, boolean>;
  executeBeforeLeave?: WopiEditButtonExecutableBeforeLeaveFunction;
}

const props = defineProps<WopiEditButtonConfig>();

let executed = false;

async function beforeLeave(event: Event): Promise<true> {
  if (props.executeBeforeLeave === undefined || executed === true) {
    return Promise.resolve(true);
  }

  event.preventDefault();

  await props.executeBeforeLeave();
  executed = true;

  const link = event.target as HTMLAnchorElement;
  link.click();

  return Promise.resolve(true);
}
</script>

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