<template>
  <ButtonQuestion
    v-model="selectedValue"
    :answers="answersFromCms"
    groupName="VinLookupMethodsOption"
    buttonTypeString="listButton"
    :questionText="questionTextFromCms"
    :questionTextClasses="['text-center']"
    isRequired
    :validationRules="rules.optionRequired"
    data-test-id="vin-lookup-methods-button-question" />
</template>

<script>

// Import Other Supporting Files
import { useMainStore } from '@/store';
import vinLookupMethodSelections from '@/constants/vin-lookup-methods';
import settleAllPromises from '@/helpers/layout-helper';
import globalRules from '@/constants/global-rules';

// Import Component
import ButtonQuestion from '@/digital-components/button-question/button-question.vue';

export default {
    name: 'vin-lookup-methods',
    components: {
        ButtonQuestion
    },
    props: {
        modelValue: String,
        cmsWidgetName: {
            type: String,
            required: true
        }
    },
    emits: ['update:modelValue'],
    data() {
        return {
            questionTextFromCms: '',
            answersFromCms: [],
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    computed: {
        selectedValue: {
            get() {
                return this.modelValue;
            },
            set(newValue) {
                this.$emit('update:modelValue', newValue);
            }
        }
    },
    methods: {
        async initializeComponent() {
            const isVinbyAddressPermissible = await this.getIsVinbyAddressPermissible();
            this.questionTextFromCms = this.getCmsContent(this.cmsWidgetName, 'QuestionText');

            const answers = this.getCmsContent(this.cmsWidgetName, 'Answers');
            if (Array.isArray(answers)) {
                if (!isVinbyAddressPermissible) {
                    answers.splice(answers.indexOf(vinLookupMethodSelections.HOMEADDRESS), 1);
                }
                this.answersFromCms = answers;
            }
        },
        async getIsVinbyAddressPermissible() {
            const isVinbyAddressPermissibleResponse = useMainStore().getIsVinbyAddressPermissible();
            // Settle promises and get results
            const promiseResultMap = [
                {
                    resultKey: 'isVinbyAddressPermissible',
                    promise: isVinbyAddressPermissibleResponse
                }
            ];

            const resultMap = await settleAllPromises(promiseResultMap);
            return resultMap.isVinbyAddressPermissible;
        }
    }
};
</script>
