interface RowKey {
  value: string;
  text: string;
}

interface Question {
  correctAnswer: any;
  getType: () => string;
  rows: any[];
  columns: any[];
  title: string;
}

const extractAnswerFromQuestion = (previous: any[], question: Question) => {
  if (!question.correctAnswer) {
    return [...previous];
  }
  let answer = question.correctAnswer;
  const type = question.getType();
  if (type === 'matrix' || type === 'matrixdropdown') {
    const correctAnswer = question.correctAnswer;
    const { rows } = question;

    answer = rows.map(({ text, value }: RowKey) => {
      const labelWitoutPunctuation = /[,.!?]/.test(text.slice(-1)) ? text.slice(0, -1) : text; // the last character might be a period, comma, question or exclamation mark. If not, we just return the key as-is
      let answer;
      if (type === 'matrix') {
        answer = correctAnswer[value] || correctAnswer[labelWitoutPunctuation]; // the key might be with or without the punctuation, can be inconsistent depending on the survey
      } else {
        const answers = correctAnswer[value] || correctAnswer[labelWitoutPunctuation]; // the key might be with or without the punctuation, can be inconsistent depending on the survey
        answer = Object.keys(answers).join(', ');
        console.log(answer);
      }
      return `${labelWitoutPunctuation}: ${answer}`; // return the key without punctuation, as we add the colon
    }); // return an array, it gets converted to a string further up
  }
  return [...previous, { title: question.title, answer, type }];
};

export const extractSurveySolutions = (prev: any[], element: any) => {
  if (!element || !element.elements) {
    // element does not exist or does not have children, so just return the previous result
    return prev;
  }
  return [...prev, ...element.elements.reduce(extractAnswerFromQuestion, [])];
};
