<script setup>
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import { useArrayData } from 'src/composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';
import VnInputPassword from 'src/components/common/VnInputPassword.vue';

const { t } = useI18n();
const { notify } = useNotify();

const arrayData = useArrayData('AccountLdap');
const URL_UPDATE = `LdapConfigs/${1}`;
const URL_CREATE = `LdapConfigs`;
const DEFAULT_DATA = {
    id: 1,
    hasData: false,
    groupDn: null,
    password: null,
    rdn: null,
    server: null,
    userDn: null,
};
const initialData = ref({
    ...DEFAULT_DATA,
});
const hasData = computed({
    get: () => initialData.value.hasData,
    set: (val) => {
        initialData.value.hasData = val;
        if (!val) formCustomFn.value = deleteMailForward;
        else formCustomFn.value = null;
    },
});
const initialDataLoaded = ref(false);
const formUrlCreate = ref(null);
const formUrlUpdate = ref(null);
const formCustomFn = ref(null);
const onTestConection = async () => {
    await axios.get(`LdapConfigs/test`);
    notify(t('LDAP connection established!'), 'positive');
};
const getInitialLdapConfig = async () => {
    try {
        initialDataLoaded.value = false;
        const { data } = await axios.get(URL_UPDATE);
        initialData.value = data;
        hasData.value = true;
        return data;
    } catch (error) {
        hasData.value = false;
        arrayData.destroy();
        console.error('Error fetching initial LDAP config', error);
        return null;
    } finally {
        // Si asignamos un valor a urlUpdate, debemos asignar null a urlCreate y viceversa, ya puede causar problemas en formModel
        if (hasData.value) {
            formUrlUpdate.value = URL_UPDATE;
            formUrlCreate.value = null;
        } else {
            formUrlUpdate.value = null;
            formUrlCreate.value = URL_CREATE;
        }
        initialDataLoaded.value = true;
    }
};
const deleteMailForward = async () => {
    await axios.delete(URL_UPDATE);
    initialData.value = { ...DEFAULT_DATA };
    hasData.value = false;
    notify(t('globals.dataSaved'), 'positive');
};

onMounted(async () => await getInitialLdapConfig());
</script>

<template>
    <QPage>
        <VnSubToolbar />
        <FormModel
            :key="initialDataLoaded"
            model="AccountLdap"
            :form-initial-data="initialData"
            :url-create="formUrlCreate"
            :url-update="formUrlUpdate"
            :save-fn="formCustomFn"
            auto-load
            @on-data-saved="getInitialLdapConfig()"
        >
            <template #moreActions>
                <QBtn
                    class="q-ml-none"
                    color="primary"
                    :label="t('account.card.testConnection')"
                    @click="onTestConection()"
                >
                    <QTooltip>
                        {{ t('account.card.testConnection') }}
                    </QTooltip>
                </QBtn>
            </template>
            <template #form="{ data, validate }">
                <VnRow class="row q-gutter-md">
                    <div class="col">
                        <QCheckbox
                            :label="t('account.card.enableSync')"
                            v-model="data.hasData"
                            @update:model-value="($event) => (hasData = $event)"
                            :toggle-indeterminate="false"
                        />
                    </div>
                </VnRow>
                <template v-if="hasData">
                    <VnInput
                        :label="t('ldap.server')"
                        clearable
                        v-model="data.server"
                        :required="true"
                        :rules="validate('LdapConfig.server')"
                    />
                    <VnInput
                        :label="t('ldap.rdn')"
                        clearable
                        v-model="data.rdn"
                        :required="true"
                        :rules="validate('LdapConfig.rdn')"
                    />
                    <VnInputPassword
                        :label="t('ldap.password')"
                        clearable
                        v-model="data.password"
                        :required="true"
                        :rules="validate('LdapConfig.password')"
                    />
                    <VnInput :label="t('ldap.userDN')" clearable v-model="data.userDn" />
                    <VnInput
                        :label="t('account.card.groupDN')"
                        clearable
                        v-model="data.groupDn"
                    />
                </template>
            </template>
        </FormModel>
    </QPage>
</template>

<i18n>
es:
    LDAP connection established!: ¡Conexión con LDAP establecida!
</i18n>
