<script setup>
import { useI18n } from 'vue-i18n';
import { ref, computed } from 'vue';
import { useStateStore } from 'stores/useStateStore';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import { useQuasar } from 'quasar';

import VnTable from 'components/VnTable/VnTable.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import FetchData from 'src/components/FetchData.vue';
import { useValidator } from 'src/composables/useValidator';

defineProps({
    id: {
        type: Number,
        default: 0,
    },
});

const { notify } = useNotify();
const { t } = useI18n();
const stateStore = useStateStore();
const quasar = useQuasar();

const tableRef = ref();
const roles = ref();
const validationsStore = useValidator();
const { models } = validationsStore;
const exprBuilder = (param, value) => {
    switch (param) {
        case 'search':
            return {
                or: [
                    { model: { like: `%${value}%` } },
                    { property: { like: `%${value}%` } },
                ],
            };
        default:
            return { [param]: value };
    }
};

const columns = computed(() => [
    {
        align: 'left',
        name: 'id',
        label: t('id'),
        isId: true,
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'model',
        label: t('model'),
        cardVisible: true,
        create: true,
        columnCreate: {
            label: t('model'),
            component: 'select',
            attrs: {
                options: Object.keys(models),
            },
        },
    },
    {
        align: 'left',
        name: 'principalId',
        label: t('principalId'),
        cardVisible: true,
        component: 'select',
        attrs: {
            options: roles,
            optionLabel: 'name',
            optionValue: 'name',
            inputDebounce: 0,
        },
        create: true,
    },
    {
        align: 'left',
        name: 'property',
        label: t('property'),
        cardVisible: true,
        create: true,
    },
    {
        align: 'left',
        name: 'accessType',
        label: t('accessType'),
        component: 'select',
        attrs: {
            options: ['READ', 'WRITE', '*'],
        },
        cardVisible: true,
        create: true,
    },
    {
        align: 'right',
        label: '',
        name: 'tableActions',
        actions: [
            {
                title: t('Delete'),
                icon: 'delete',
                action: deleteAcl,
                isPrimary: true,
            },
        ],
    },
]);
const deleteAcl = async ({ id }) => {
    try {
        await new Promise((resolve) => {
            quasar
                .dialog({
                    component: VnConfirm,
                    componentProps: {
                        title: t('Remove ACL'),
                        message: t('Do you want to remove this ACL?'),
                    },
                })
                .onOk(() => {
                    resolve(true);
                })
                .onCancel(() => {
                    resolve(false);
                });
        });
        await axios.delete(`ACLs/${id}`);
        tableRef.value.reload();
        notify('ACL removed', 'positive');
    } catch (error) {
        console.error('Error deleting Acl: ', error);
    }
};
</script>

<template>
    <VnSearchbar
        data-key="AccountAcls"
        url="ACLs"
        :expr-builder="exprBuilder"
        :label="t('acls.search')"
        :info="t('acls.searchInfo')"
    />
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
    </QDrawer>
    <FetchData
        url="VnRoles?fields=['name']"
        auto-load
        @on-fetch="(data) => (roles = data)"
    />
    <VnTable
        ref="tableRef"
        data-key="AccountAcls"
        :url="`ACLs`"
        :create="{
            urlCreate: 'ACLs',
            title: 'Create ACL',
            onDataSaved: () => tableRef.reload(),
            formInitialData: {},
        }"
        order="id DESC"
        :disable-option="{ card: true }"
        :columns="columns"
        default-mode="table"
        :right-search="true"
        :is-editable="true"
        :use-model="true"
    />
</template>

<i18n>
es:
    New ACL: Nuevo ACL
    ACL removed: ACL eliminado
    ACL will be removed: El ACL será eliminado
    Are you sure you want to continue?: ¿Seguro que quieres continuar?
    Remove ACL: Eliminar Acl
    Do you want to remove this ACL?: ¿Quieres eliminar este ACL?
    principalId: Rol
    model: Modelo
en:
    New ACL: New ACL
    ACL removed: ACL removed
    ACL will be removed: ACL will be removed
    Are you sure you want to continue?: Are you sure you want to continue?
    Remove ACL: Remove ACL
    Do you want to remove this ACL?: Do you want to remove this ACL?
    principalId: Rol
    model: Models
</i18n>
