<script setup lang="ts">
import FontAwesomeIcon from "@/components/FontAwesomeIcon.vue";
import { onMounted } from "vue";
import { Toast, Tooltip } from "bootstrap";
import BootstrapToast from "@/components/BootstrapToast.vue";

const props = defineProps<{
  text: string;
  button?: boolean;
}>();

let successToast: Toast | null = null;
let failToast: Toast | null = null;
const randomIDSuffix = Math.random().toString(16).substring(2, 8);

function copyToClipboard() {
  if (!navigator.clipboard) {
    failToast?.show();
  }
  navigator.clipboard
    .writeText(props.text)
    .then(() => {
      successToast?.show();
    })
    .catch(() => {
      failToast?.show();
    });
}

onMounted(() => {
  if (!props.button) {
    new Tooltip("#tooltip-" + randomIDSuffix);
  }
  successToast = new Toast("#successToast-" + randomIDSuffix);
  failToast = new Toast("#failToast-" + randomIDSuffix);
});
</script>

<template>
  <bootstrap-toast :toast-id="'successToast-' + randomIDSuffix"
    >Successfully copied to clipboard
  </bootstrap-toast>
  <bootstrap-toast
    :toast-id="'failToast-' + randomIDSuffix"
    color-class="danger"
    >Can't copy to clipboard
  </bootstrap-toast>
  <button v-if="props.button" @click="copyToClipboard" class="btn btn-primary">
    Copy to Clipboard
  </button>
  <span
    v-else
    class="hover-info cursor-pointer"
    data-bs-toggle="tooltip"
    data-bs-title="Copy to Clipboard"
    :id="'tooltip-' + randomIDSuffix"
  >
    <font-awesome-icon icon="fa-solid fa-clipboard" @click="copyToClipboard" />
  </span>
</template>

<style scoped></style>