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

<template>
  <main>
    <v-btn :icon="true" @click="alertDeleteItem()">
      <v-icon>mdi-delete</v-icon>
    </v-btn>

    <LazyLayoutDialog
      :show="showDialog"
    >
      <template #dialogType>{{ $t('delete_assistant') }}</template>
      <template #dialogTitle>{{ $t('attention') }}</template>
      <template #dialogText>
        <v-card-text>
          <p>{{ $t('confirm_to_delete') }}</p>
        </v-card-text>
      </template>
      <template #dialogBtn>
        <v-btn class="mr-4 submitBtn ot-grey ot-white--text" @click="closeDialog">
          {{ $t('cancel') }}
        </v-btn>
        <v-btn class="mr-4 submitBtn ot-danger ot-white--text" @click="deleteItem">
          {{ $t('delete') }}
        </v-btn>
      </template>
    </LazyLayoutDialog>
  </main>
</template>

<script setup lang="ts">
import {TYPE_ALERT} from '~/types/enum/enums'
import {Ref} from "@vue/reactivity";
import {useEntityManager} from "~/composables/data/useEntityManager";
import ApiResource from "~/models/ApiResource";
import {usePageStore} from "~/stores/page";

const props = defineProps({
    model: {
      type: Object,
      required: true
    },
    entity: {
      type: Object as () => ApiResource,
      required: true
    }
})

const showDialog: Ref<boolean> = ref(false)

const { em } = useEntityManager()

const deleteItem = async () => {
  try {
    await em.delete(props.model, props.entity)
    usePageStore().addAlerts(TYPE_ALERT.SUCCESS, ['deleteSuccess'])
  } catch (error: any) {
    usePageStore().addAlerts(TYPE_ALERT.ALERT, [error.message])
  }
  showDialog.value = false
}

const alertDeleteItem = () => { showDialog.value = true }
const closeDialog = () => { showDialog.value = false }

</script>

<style scoped>
</style>
