<template>
    <div
        v-for="(q, i) in questions"
        :key="i"
        class="questionBlock">
        <transition
            appear
            name="fade"
            mode="out-in">
            <buttonQuestion
                v-if="q.answerSelected || q.questionSequence === currentQuestionNum"
                class="radioQuestion"
                :class="q.questionSequence === currentQuestionNum && 'current-question'"
                :questionText="q.questionText"
                :answers="q.answers"
                :groupName="`question-${index}-${q.questionSequence}`"
                :modelValue="q.answerSelected"
                isRequired
                :validationRules="validationRules"
                :buttonTypeString="'listButtonHorizontal'"
                @update:modelValue="handleAnswer(q, $event)" />
        </transition>
    </div>
</template>

<script>
import buttonQuestion from '@/digital-components/button-question/button-question.vue';
import { useValidateForm } from 'vee-validate';

export default {
    name: 'question-chain',
    components: {
        buttonQuestion
    },
    props: {
        questionData: Array,
        validationRules: String,
        modelValue: Object,
        index: Number,
        answerKey: String
    },
    emits: ['update:modelValue'],
    data() {
        return {
            currentQuestionNum: 0,
            questions: []
        };
    },
    async created() {
        // do a test validation check upon create to prevent out of sync / incorrect valid states
        // NOTE: needs to have async/await here; tested and won't work without it
        await useValidateForm();

        this.questionData.map((q) => {
            const question = {
                questionText: q.questionText,
                questionSequence: q.questionSequence,
                answers: q.answers.map((a) => ({
                    buttonLabel: a.answerText,
                    // Name will either be nextQuestionSequence or answerResult
                    // Name will be used by list-button as the input value.
                    // It must be a single string or number, so concatenating together a string with
                    //       4 pieces of data separated by pipe characters:
                    //       question number|type of answer|answer value|answer text
                    value: a.nextQuestionSequence
                        ? `${q.questionSequence
                        }|nextQuestion|${
                            a.nextQuestionSequence
                        }|${
                            a.answerText}`
                        : `${q.questionSequence}|answer|${a.answerResult}|${a.answerText}`,
                    nextQuestionSequence: a.nextQuestionSequence,
                    answerResult: a.answerResult,
                    questionSequence: q.questionSequence,
                    questionType: a.nextQuestionSequence ? 'nextQuestion' : 'answer'
                })),
                answerSelected: q.answerSelected || ''
            };
            if (!q.suppressThisQuestion) {
                this.questions.push(question);
            }
            return q;
        });

        if (!this.modelValue?.length > 0 && this.questions.length > 0) {
            // set this.currentQuestionNum to first valid question
            this.currentQuestionNum = this.questions[0].questionSequence;
        }
    },
    methods: {
        handleAnswer(question, returnedAnswer) {
            /*
                returnedAnswer example format:
                "1|answer|DD11132|Yes"
            */

            // TODO: Assignment to parm
            question.answerSelected = returnedAnswer;
            const isQuestionChainComplete = this.getQuestionChainAnswerIfComplete(returnedAnswer);

            if (isQuestionChainComplete) {
                this.$emit('update:modelValue', isQuestionChainComplete);
            }
        },
        getQuestionChainAnswerIfComplete(returnedAnswer) {
            // this method will return either a final answer or Boolean false
            if (!returnedAnswer) {
                return false;
            }

            // Example returnedAnswers:
            //   "1|nextQuestion|3|No"
            //   "5|answer|DW02104|Yes"

            const returnedAnswerArray = returnedAnswer.split('|');
            const questionNum = parseInt(returnedAnswerArray[0], 10);
            const questionType = returnedAnswerArray[1];
            const questionAnswer = returnedAnswerArray[2];
            const questionAnswerText = returnedAnswerArray[3];
            const answeredQuestions = [];

            // TODO: This forEach could probably be converted into something more reactive
            this.questions.forEach((q) => {
                // find this question and mark it as "answered" by populating answerSelected
                if (q.questionSequence === questionNum) {
                    q.answerSelected = returnedAnswer;
                    q.answerNumber = questionNum;
                    q.selectedAnswerText = questionAnswerText;
                }
                // remove all answers AFTER this question...
                //      (needed in case user is changing previously answered questions)
                if (q.questionSequence > questionNum) {
                    delete q.answerSelected;
                }
                if (q.answerSelected) {
                    answeredQuestions.push({
                        questionText: q.questionText,
                        selectedAnswerText: q.answerSelected.split('|')[3],
                        questionNum: q.questionSequence
                    });
                }
            });

            // return false if there's a nextQuestion...
            // or return an object with final answers(truthy)
            if (questionType === 'nextQuestion') {
                // update to next question index
                // update count to display next question
                this.currentQuestionNum = parseInt(questionAnswer, 10);
                return false;
            }
            // reset current question index (removes .current-question class)
            this.currentQuestionNum = 0; // reset count

            // return an object with the part answer, all the answered questions, and the part index
            return {
                answerResult: questionAnswer,
                answeredQuestions,
                index: this.index
            };
        }
    }
};
</script>
<style lang="scss" scoped>
.questionBlock {
    .radioQuestion {
        margin-bottom: 1rem;
    }
    &:not(:first-of-type) {
        .radioQuestion {
            padding-top: 1rem;
        }
    }
}
</style>
