<template>
    <div v-for="(q, i) in questions" :key="i">
        <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="`${keyString}-${q.questionSequence}`"
                v-model="q.answerSelected"
                @isCheckedChanged="handleChainCompleted"
                isRequired
                :validationRules="validationRules"
            />
        </transition>
    </div>
</template>

<script>
import buttonQuestion from "@/common-components/button-question/button-question";
import { useValidateForm } from "vee-validate";

export default {
  name: "questionChain",
  data() {
    return {
      currentQuestionNum: 0,
      questions: [],
    };
  },
  props: {
    questionData: Object,
    validationRules: String,
    modelValue: Array,
    partIndex:  Number,
    keyString: String,
  },
  async created() {
    // validate form upon create to prevent out of sync / persistent valid states
    await useValidateForm(); // do a test validation check, without triggering full validation

    this.questionData.map((q, i) => {
      let answerPair = [];
      const question = {
        questionText: q.questionText,
        questionSequence: q.questionSequence,
        answers: q.answers.map((a) => {
            answerPair.push(a.nextQuestionSequence ? a.nextQuestionSequence : a.answerResult);
            return {
                Text: 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
                Name: a.nextQuestionSequence ? 
                  q.questionSequence + "|nextQuestion|" + a.nextQuestionSequence + "|" + a.answerText : 
                  q.questionSequence + "|answer|" + a.answerResult + "|" + a.answerText,
                nextQuestionSequence: a.nextQuestionSequence,
            }
        }),
        answerSelected: q.answerSelected || "",
      };
      question.answerPair = answerPair;
      if (!q.isDuplicateQuestion) {
        this.questions.push(question);
      }
    });

    if (!this.modelValue?.length > 0) {
      // set this.currentQuestionNum to first valid question
      this.currentQuestionNum = this.questions[0].questionSequence;
      // scroll the next question into view
      this.$nextTick(() => {
          document.querySelector('.current-question').scrollIntoView({behavior: "smooth"});
      })
    }

  },
  methods: {
    handleChainCompleted(returnedAnswer) {
      const isQuestionChainComplete = this.handleReturnedAnswer(returnedAnswer.value);

      if (isQuestionChainComplete) {
        this.$emit("update:modelValue", isQuestionChainComplete);
      }
    },
    handleReturnedAnswer(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]);
      const questionType = returnedAnswerArray[1];
      const questionAnswer = returnedAnswerArray[2];
      const questionAnswerText = returnedAnswerArray[3];

      this.questions.forEach((q) => {
        // mark this question as "answered"
        if (q.questionSequence === questionNum) {
          q.answerSelected = returnedAnswer;
          q.answerNumber = questionNum;
        }
        // remove all previous answers after the index of this one in questions
        if ((q.questionSequence > questionNum)) {
          delete q.answerSelected;
        }
      });

      // return false if there's a nextQuestion... or return an object with "final" answers
      if (questionType === "nextQuestion") {
        // update to next question index
        this.currentQuestionNum = parseInt(questionAnswer); // update count to display next question
        // scroll the next question into view
        this.$nextTick(() => {
            document.querySelector('.current-question').scrollIntoView({behavior: "smooth"});
        })
        return false;
      } else {
        const answeredQuestions = [];
        this.questions.forEach(( q ) => {
          if (q.answerSelected) {
            answeredQuestions.push({
              questionText: q.questionText,
              selectedAnswerText: q.answerSelected.split("|")[3],
              questionNum: q.questionSequence,
            });
          }
        });
        // reset current question index
        this.currentQuestionNum = 0; // reset count

        return {
            answerResult: questionAnswer,
            answeredQuestions: answeredQuestions,
            partIndex: this.partIndex,
        };

      }
    },
  },
  components: {
    buttonQuestion,
  },
};
</script>
