<template>
    <div class="settings-widget">
        <table>
            <tr v-for="setting in settings" :key="setting.id">
                <td>
                    <InputStringWidget v-if="setting.datatype == 'string'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value=setting.value
                        :list="languagesList()" @input="handleInput(setting.id, $event)" />

                    <DateInputWidget v-else-if="setting.datatype == 'date'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value=setting.value
                        @input="handleInput(setting.id, $event)" />

                    <SelectDropdownWidget v-else-if="setting.datatype == 'singleselect'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value=setting.value
                        :list="getSettingOptions(setting.name, setting.options)"
                        @input="handleInput(setting.id, $event)" />

                    <InputNumberWidget v-else-if="setting.datatype == 'int'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value="convertToInt(setting.value)"
                        min="0" max="200" @input="handleInput(setting.id, $event)" />

                    <FloatInputWidget v-else-if="setting.datatype == 'float'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value="convertToFloat(setting.value)"
                        @input="handleInput(setting.id, $event)" />

                    <CheckboxWidget v-else-if="setting.datatype == 'bool'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value="convertToBool(setting.value)"
                        @input="handleInput(setting.id, $event)" />

                    <MultiselectWidget v-else-if="setting.datatype == 'multiselect'"
                        :labelTr="`settings.personal.label.${setting.name}`"
                        :tooltipTr="`settings.personal.tooltip.${setting.name}`" :value="setting.value"
                        :list="getSettingOptions(setting.name, setting.options)"
                        @input="handleInput(setting.id, $event)" />

                    <div v-else>{{ setting }}</div>
                    <span v-if="setting.unit">&nbsp;{{ setting.unit }}</span>
                </td>
                <td>
                    <select v-model="setting.visibility.id"
                        @change="handleVisibilityChange(setting.id, setting.visibility.id)">
                        <option v-for="visibility in possibleVisibilities" :key="visibility.id" :value="visibility.id">
                            {{ $t(`settings.visibility.${visibility.description}`) }}
                        </option>
                    </select>
                </td>
            </tr>
        </table>
    </div>
</template>

<script>
import apiClient from '@/utils/axios.js';
import { mapGetters } from 'vuex';
import InputStringWidget from '@/components/form/InputStringWidget.vue';
import DateInputWidget from '@/components/form/DateInputWidget.vue';
import SelectDropdownWidget from '@/components/form/SelectDropdownWidget.vue';
import InputNumberWidget from '@/components/form/InputNumberWidget.vue';
import FloatInputWidget from '@/components/form/FloatInputWidget.vue';
import CheckboxWidget from '@/components/form/CheckboxWidget.vue';
import MultiselectWidget from '@/components/form/MultiselectWidget.vue';

export default {
    name: "SettingsWidget",
    components: {
        InputStringWidget,
        DateInputWidget,
        SelectDropdownWidget,
        InputNumberWidget,
        FloatInputWidget,
        CheckboxWidget,
        MultiselectWidget
    },
    props: {
        settingsType: {
            type: String,
            required: true
        } 
    }, 
    data: {
        settings: [],
        possibleVisibilities: [],
    },
    computed: {
        ...mapGetters(['user']),
    }, 
    async mounted() {
        await this.fetchSettings();
    }, 
    methods: {
        async fetchSettings() {
            if (this.user && this.user.id) {
                try {
                    const visibilityResponse = await apiClient.get('/api/settings/visibilities');
                    this.possibleVisibilities = visibilityResponse.data;
                    const userid = this.user.id;
                    const response = await apiClient.post('/api/settings/filter', {
                        userid: userid,
                        type: this.settingsType
                    });
                    this.settings = response.data;
                } catch (err) {
                    this.settings = [];
                }
            }
        },
        getSettingOptions(fieldName, options) {
            return options.map((option) => {
                return {
                    value: option.id,
                    captionTr: `settings.personal.${fieldName}.${option.value}`
                }
            });
        },
        async handleInput(settingId, value) {
            if (['object', 'array'].includes(typeof value)) {
                return;
            }
            try {
                const userid = this.user.id;
                await apiClient.post('/api/settings/update', {
                    userid: userid,
                    settingId: settingId,
                    value: value
                });
                this.fetchSettings();
            } catch (err) {
                console.error('Error updating setting:', err);
            }
        },
        languagesList() {
            return [
                { value: 'en', captionTr: 'settings.personal.languages.en' },
                { value: 'de', captionTr: 'settings.personal.languages.de' },
            ];
        },
        convertToInt(value) {
            const intValue = parseInt(value, 10);
            return isNaN(intValue) ? 0 : intValue;
        },
        convertToFloat(value) {
            const floatValue = parseFloat(value);
            return isNaN(floatValue) ? 0.0 : floatValue;
        },
        convertToBool(value) {
            if (value === 'true' || value === true) {
                return true;
            } else if (value === 'false' || value === false) {
                return false;
            } else {
                return false;
            }
        },
        async handleVisibilityChange(settingId, visibilityId) {
            try {
                await apiClient.post('/api/settings/update-visibility', {
                    userParamTypeId: settingId,
                    visibilityId: visibilityId
                });
            } catch (err) {
                console.error('Error updating visibility:', err);
            }
        },
    },
    data() {
        return {
            settings: [],
        };
    }
};
</script>

<style lang="scss" scoped>
    label {
        float: left;
    }
</style>