<script setup>
import { onBeforeMount, watch, computed, ref } from 'vue';
import { useArrayData } from 'composables/useArrayData';
import { useState } from 'src/composables/useState';
import { useRoute } from 'vue-router';
import VnDescriptor from './VnDescriptor.vue';

const $props = defineProps({
    url: {
        type: String,
        default: '',
    },
    filter: {
        type: Object,
        default: null,
    },
    dataKey: {
        type: String,
        default: null,
    },
});

const state = useState();
const route = useRoute();
let arrayData;
let store;
let entity;
const isLoading = ref(false);
const isSameDataKey = computed(() => $props.dataKey === route.meta.moduleName);
defineExpose({ getData });

onBeforeMount(async () => {
    arrayData = useArrayData($props.dataKey, {
        url: $props.url,
        userFilter: $props.filter,
        skip: 0,
        oneRecord: true,
    });
    store = arrayData.store;
    entity = computed(() => {
        const data = store.data ?? {};
        if (data) emit('onFetch', data);
        return data;
    });

    // It enables to load data only once if the module is the same as the dataKey
    if (!isSameDataKey.value || !route.params.id) await getData();
    watch(
        () => [$props.url, $props.filter],
        async () => {
            if (!isSameDataKey.value) await getData();
        },
    );
});

async function getData() {
    store.url = $props.url;
    store.filter = $props.filter ?? {};
    isLoading.value = true;
    try {
        await arrayData.fetch({ append: false, updateRouter: false });
        const { data } = store;
        state.set($props.dataKey, data);
        emit('onFetch', data);
    } finally {
        isLoading.value = false;
    }
}

const emit = defineEmits(['onFetch']);
</script>

<template>
    <VnDescriptor v-model="entity" v-bind="$attrs" :module="dataKey">
        <template v-for="(_, slotName) in $slots" #[slotName]="slotData" :key="slotName">
            <slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
        </template>
    </VnDescriptor>
</template>
