<template>
  <dropdownQuestion
    v-model="selectedValue"
    :options="values"
    disableAutoFill
    :placeHolderText="isDisabled ? '' : placeHolderText"
    :cmsWidgetName="cmsWidgetName"
    :isDisabled="isDisabled" />
</template>

<script>

import dropdownQuestion from '@/digital-components/dropdown-question/dropdown-question.vue';

export default {
    name: 'vehicle-question',
    components: {
        dropdownQuestion
    },
    props: {
        modelValue: String,
        updateValues: Function,
        cmsWidgetName: String
    },
    emits: ['update:modelValue'],
    data() {
        return {
            values: [],
            selectedIndex: null
        };
    },
    computed: {
        selectedValue: {
            get() {
                return this.selectedIndex?.toString();
            },
            set(newIndex) {
                this.selectedIndex = newIndex;
                const newValue = newIndex != null && newIndex > -1 ? this.values[newIndex] : null;
                this.$emit('update:modelValue', newValue);
            }
        },
        isDisabled() {
            return this.values.length === 0;
        },
        placeHolderText() {
            return this.getCmsContent(this.cmsWidgetName, 'ButtonText');
        }
    },
    methods: {
        async getNewValues() {
            const results = await this.updateValues();
            this.values = results?.data;
            if (this.values.length === 1) {
                this.selectedValue = 0;
            } else {
                const valueIndex = this.values.indexOf(this.modelValue);
                this.selectedValue = valueIndex === -1 ? null : valueIndex;
            }
        },
        clearValues() {
            this.values = [];
            this.selectedValue = null;
        }
    }
};
</script>
