<!--
Bouton Delete avec modale de confirmation de la suppression
-->

<template>
  <main>
    <div @click="onDeleteClicked()" class="div_to_clicked">
      <!-- Content -->
      <slot/>
    </div>

    <UiFormDeletionConfirmationDialog
      v-model="showDeletionConfirmationDialog"
      @delete-clicked="onDeleteConfirmed"
      @cancel-clicked="onCancelClicked"
    />
  </main>
</template>

<script setup lang="ts" generic="T extends ApiResource">
import {type Ref, ref} from 'vue'
import type ApiResource from '~/models/ApiResource'
import { useDeleteItem } from '~/composables/form/useDeleteItem'
import {useEntityManager} from "~/composables/data/useEntityManager";

const props = defineProps<{
  entity: T
}>()

const { deleteItem } = useDeleteItem()
const pageStore = usePageStore()
const { em } = useEntityManager()

const showDeletionConfirmationDialog: Ref<boolean> = ref(false)
const itemToDelete: Ref<ApiResource | null> = ref(null)

const onDeleteClicked =  () => {
  itemToDelete.value = em.cast(em.getModel(props.entity), props.entity)
  showDeletionConfirmationDialog.value = true
}

const onCancelClicked = () => {
  itemToDelete.value = null
}

const onDeleteConfirmed = async () => {
  if(itemToDelete.value != null){
    pageStore.loading = true
    await deleteItem(itemToDelete.value)
    pageStore.loading = false
  }
}

</script>

<style scoped>
.div_to_clicked{
  cursor: pointer;
}
</style>
