<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <questions-page
            ref="questionsPage"
            :isMetaValid="meta.valid"
            :alertFewMoreQuestionsHeader="AlertFewMoreQuestionsHeader"
            :alertFewMoreQuestionsCopy="AlertFewMoreQuestionsCopy"
            :questionsData="questionsData"
            :validationRules="questions - required"
            v-model="selectedAnswers"
            @forwardButtonAction="forwardButtonAction"
            @backButtonAction="backButtonAction"
            :currentGlassPieceIndex="currentGlassPieceIndex" />
    </Form>
</template>

<script>
// Components
import questionsPage from "@/common-components/questions-page/questions-page";

// Supporting Files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import store from "@/store";
import { fmgPageValues } from "@/router/router-constants/fmgPage-values";
import { Form, defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import vehicleQuestionsMixin from "@/mixins/vehicle-questions-mixin";

// DEFINE VALIDATION RULES
defineRule("questions-required", required(errorMessages.OPTION_REQUIRED));

export default {
    name: "capability-questions",
    mixins: [vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    data() {
        return {
            questionsData: [],
            selectedAnswers: {},
            currentGlassPieceIndex: 0,
        };
    },
    computed: {
        AlertFewMoreQuestionsHeader() {
            return this.getCmsContent("AdditionalPartsQuestionsAlert", "HeadlineText");
        },
        AlertFewMoreQuestionsCopy() {
            return this.getCmsContent("AdditionalPartsQuestionsAlert", "BodyText");
        },
        pageData() {
            return this.$store.getters.pageData(fmgPageValues.CAPABILITY_QUESTIONS);
        },
    },
    mounted() {
        // are there alreadyAnsweredQuestions?
        const alreadyAnsweredQuestions = store.getters.damage.capabilityQuestionAnswers;

        this.questionsData = this.pageData.partsOrQuestions
            .filter((x) => x.capabilityQuestions)
            .map((glassPiece, i) => {
                // NOTE: questions for property "questions" can differ between layouts
                glassPiece.questions = glassPiece.capabilityQuestions;
                glassPiece.answerKey = glassPiece.glassLocation + "-" + glassPiece.glassName;
                // reset selectedAnswers for this glassPiece
                this.selectedAnswers[glassPiece.answerKey] = [];

                const updatedGlassPiece = this.setupInitialData(
                    glassPiece,
                    i,
                    alreadyAnsweredQuestions
                );

                // Set up watch for each set of glass questions
                this.$watch(
                    "selectedAnswers." + glassPiece.answerKey,
                    (newValue) => {
                        if (newValue && Object.keys(newValue).length > 0) {
                            this.handleAnswerUpdates(newValue, glassPiece.answerKey);
                        }
                    },
                    { deep: true }
                );

                return updatedGlassPiece;
            });
    },
    methods: {
        arePagePrerequisitesValid() {
            const capabilityQuestionsPageData = store.getters.pageData(
                fmgPageValues.CAPABILITY_QUESTIONS
            );
            return (
                capabilityQuestionsPageData && Object.keys(capabilityQuestionsPageData).length > 0
            );
        },
        async forwardButtonAction() {
            const questionAnswersArray = this.questionsData.map((glass) => {
                // get answerResult2 of returned answer
                let selectedAnswerResult2;
                glass.questions.forEach((q) => {
                    const idx = q.answers.findIndex(
                        (a) => a.answerResult === glass.answerData.answerResult
                    );
                    if (idx !== -1) {
                        selectedAnswerResult2 = q.answers[idx].answerResult2;
                    }
                });

                return {
                    glassLocation: glass.glassLocation,
                    glassName: glass.glassName,
                    result: glass.answerData.answerResult,
                    result1: glass.answerData.answerResult,
                    result2: selectedAnswerResult2,
                    answeredQuestions: glass.answerData.answeredQuestions,
                    isSuppressedPart: glass.isSuppressedPart,
                };
            });

            // clear out answerData for future page loads; must occur prior to store save
            this.questionsData.forEach((glass) => {
                glass.answerData = {};
            });

            // save to vuex store as order.damage.capabilityQuestionAnswers (array)
            await this.dispatchStoreAction(
                this.storeActions.SAVE_CAPABILITY_QUESTION_ANSWERS,
                questionAnswersArray,
                false
            );

            // get parts from the capabilityQuestionAnswers
            const partsOrQuestions = this.pageData.partsOrQuestions;
            for (let answer of questionAnswersArray) {
                const partFromCapabilityQuestionAnswer = (
                    await this.dispatchStoreAction(
                        this.storeActions.GET_PART_FROM_CAPABILITY_QUESTION_ANSWER,
                        answer.glassLocation,
                        false
                    )
                ).data;

                partsOrQuestions.find(
                    (partOrQuestion) => partOrQuestion.glassLocation === answer.glassLocation
                ).parts = partFromCapabilityQuestionAnswer;
            }

            this.navigateForward(partsOrQuestions);
        },
    },
    components: {
        Form,
        questionsPage,
    },
};
</script>
