<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';

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 () => {
    try {
        await axios.get(`LdapConfigs/test`);
        notify(t('LDAP connection established!'), 'positive');
    } catch (error) {
        console.error('Error testing connection', error);
    }
};
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 () => {
    try {
        await axios.delete(URL_UPDATE);
        initialData.value = { ...DEFAULT_DATA };
        hasData.value = false;
        notify(t('globals.dataSaved'), 'positive');
    } catch (err) {
        console.error('Error deleting mail forward', err);
    }
};

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('ldap.testConnection')"
                    @click="onTestConection()"
                >
                    <QTooltip>
                        {{ t('ldap.testConnection') }}
                    </QTooltip>
                </QBtn>
            </template>
            <template #form="{ data, validate }">
                <VnRow class="row q-gutter-md">
                    <div class="col">
                        <QCheckbox
                            :label="t('ldap.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')"
                    />
                    <VnInput
                        :label="t('ldap.password')"
                        clearable
                        type="password"
                        v-model="data.password"
                        :required="true"
                        :rules="validate('LdapConfig.password')"
                    />
                    <VnInput :label="t('ldap.userDN')" clearable v-model="data.userDn" />
                    <VnInput
                        :label="t('ldap.groupDN')"
                        clearable
                        v-model="data.groupDn"
                    />
                </template>
            </template>
        </FormModel>
    </QPage>
</template>

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