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

<template>
  <main>
    <v-btn :icon="true" :flat="flat" @click="alertDeleteItem()">
      <v-icon>fas fa-trash</v-icon>
    </v-btn>

    <LazyLayoutDialog
      :show="showDialog"
    >
      <template #dialogType>{{ $t('delete_assistant') }}</template>
      <template #dialogTitle>{{ $t('caution') }}</template>
      <template #dialogText>
        <v-card-text>
          <p>{{ $t('confirm_to_delete') }}</p>
        </v-card-text>
      </template>
      <template #dialogBtn>
        <v-btn class="mr-4 submitBtn theme-neutral-strong" @click="closeDialog">
          {{ $t('cancel') }}
        </v-btn>
        <v-btn class="mr-4 submitBtn theme-danger" @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";
import ApiModel from "~/models/ApiModel";

const props = defineProps({
    model: {
      type: Function as any as () => typeof ApiModel,
      required: true
    },
    entity: {
      type: Object as () => ApiResource,
      required: true
    },
    flat: {
      type: Boolean,
      required: false,
      default: false
    }
})

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

const { em } = useEntityManager()

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

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

</script>

<style scoped>
</style>
