const extractAnswerFromQuestion = (previous, question) => {
  if (!question.correctAnswer) {
    return [...previous];
  }
  let answer = question.correctAnswer;
  if (question.getType() === 'matrix') {
    const correctAnswer = question.correctAnswer;
    const questionRows = question.getRows();
    const keys = questionRows.map(question => question.value); // get the keys as they appear in the question

    answer = keys.map(key => {
      let keyWithoutPunctuation = /[,.!?]/.test(key.slice(-1)) ? key.slice(0, -1) : key; // the last character might be a period, comma, question or exclamation mark. If not, we just return the key as-is
      let answer = correctAnswer[key] || correctAnswer[keyWithoutPunctuation]; // the key might be with or without the punctuation, can be inconsistent depending on the survey
      return `${keyWithoutPunctuation}: ${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: question.getType()}];
};

export const extractSurveySolutions = (prev, element) => {
  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, [])];
};
