<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('AccountSamba');
const formModel = ref(null);
const URL_UPDATE = `SambaConfigs/${1}`;
const URL_CREATE = `SambaConfigs`;

const DEFAULT_DATA = {
    id: 1,
    hasData: false,
    adDomain: null,
    adController: null,
    adUser: null,
    adPassword: null,
    userDn: null,
    verifyCert: false,
};

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(`SambaConfigs/test`);
        notify(t('Samba connection established!'), 'positive');
    } catch (error) {
        console.error('Error testing connection', error);
    }
};

const getInitialSambaConfig = 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 Samba config', error);
        return null;
    } finally {
        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 getInitialSambaConfig());
</script>

<template>
    <QPage>
        <VnSubToolbar />
        <FormModel
            ref="formModel"
            :key="initialDataLoaded"
            model="AccountSamba"
            :form-initial-data="initialData"
            :url-create="formUrlCreate"
            :url-update="formUrlUpdate"
            :save-fn="formCustomFn"
            auto-load
            @on-data-saved="getInitialSambaConfig()"
        >
            <template #moreActions>
                <QBtn
                    class="q-ml-none"
                    color="primary"
                    :label="t('samba.testConnection')"
                    :disable="formModel.hasChanges"
                    @click="onTestConection()"
                >
                    <QTooltip>
                        {{ t('samba.testConnection') }}
                    </QTooltip>
                </QBtn>
            </template>
            <template #form="{ data, validate }">
                <VnRow class="row q-gutter-md">
                    <div class="col">
                        <QCheckbox
                            :label="t('samba.enableSync')"
                            v-model="data.hasData"
                            @update:model-value="($event) => (hasData = $event)"
                            :toggle-indeterminate="false"
                        />
                    </div>
                </VnRow>
                <template v-if="hasData">
                    <VnInput
                        :label="t('samba.domainAD')"
                        clearable
                        v-model="data.adDomain"
                        :required="true"
                        :rules="validate('SambaConfigs.server')"
                    />
                    <VnInput
                        :label="t('samba.domainController')"
                        clearable
                        v-model="data.adController"
                        :required="true"
                        :rules="validate('SambaConfigs.adController')"
                    />
                    <VnInput
                        :label="t('samba.userAD')"
                        clearable
                        v-model="data.adUser"
                        :rules="validate('SambaConfigs.adUser')"
                    />
                    <VnInput
                        :label="t('samba.passwordAD')"
                        clearable
                        type="password"
                        v-model="data.adPassword"
                    />
                    <VnInput
                        :label="t('samba.domainPart')"
                        clearable
                        v-model="data.userDn"
                        :required="true"
                        :rules="validate('SambaConfigs.userDn')"
                    />
                    <QCheckbox
                        :label="t('samba.verifyCertificate')"
                        v-model="data.verifyCert"
                        :rules="validate('SambaConfigs.groupDn')"
                        :toggle-indeterminate="false"
                    />
                </template>
            </template>
        </FormModel>
    </QPage>
</template>

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