const COMMON_QUESTION_TYPES = [1, 2, 3, 4, 5];

export const QUESTION_TYPES = {
  1: "SINGLE_ANSWER_QUESTION",
  2: "MULTIPLE_ANSWER_QUESTION",
  3: "BOOL_ANSWER_QUESTION",
  4: "FILL_BLANK_QUESTION",
  5: "TEXT_ANSWER_QUESTION",
  6: "READING_COMPREHENSION",
  7: "LISTENING_QUESTION",
  8: "BANKED_CLOZE",
};

// paper json
export function getPaperJsonSimpleStructInfo(paperJson) {
  let struct = [];
  paperJson.details.forEach((detail) => {
    struct.push(`detail:${detail.number}-${detail.name}`);
    detail.questions.forEach((question) => {
      if (COMMON_QUESTION_TYPES.includes(question.structType)) {
        const info = parseCommonTypeQuestion(question);
        struct.push(`${detail.number}-${info}`);
      } else {
        let infos = parseNestedTypeQuestion(question);
        infos.forEach((info) => {
          struct.push(`${detail.number}-${info}`);
        });
      }
    });
  });
  return struct.join("#");
}

function parseCommonTypeQuestion(question) {
  const structType = QUESTION_TYPES[question.structType];
  let info = `${question.number}:${structType}`;
  const choiceQs = ["SINGLE_ANSWER_QUESTION", "MULTIPLE_ANSWER_QUESTION"];
  if (choiceQs.includes(structType)) {
    info += `:${question.options.length}`;
  } else if (structType === "FILL_BLANK_QUESTION") {
    info += `:${getFillBackClozeCount(question.body)}`;
  } else {
    info += ":";
  }

  return info;
}

export function getFillBackClozeCount(questionBody) {
  let num = 0;
  try {
    questionBody.sections.forEach((section) => {
      section.blocks.forEach((block) => {
        if (block.type === "cloze") num++;
      });
    });
  } catch (error) {
    num = 1;
  }

  return num;
}

function parseNestedTypeQuestion(question) {
  let struct = [];
  let qinfo = `${question.number}`;
  question.subQuestions.forEach((subq) => {
    const info = parseCommonTypeQuestion(subq);
    struct.push(`${qinfo}-${info}`);
  });
  return struct;
}

// paper struct
export function getPaperStructSimpleStructInfo(paperStruct) {
  let struct = [];
  paperStruct.details.forEach((detail) => {
    struct.push(`detail:${detail.number}-${detail.name}`);
    detail.units.forEach((question) => {
      if (COMMON_QUESTION_TYPES.includes(question.type)) {
        const info = parseStructCommonTypeQuestion(question);
        struct.push(`${detail.number}-${info}`);
      }
    });
  });
  return struct.join("#");
}

function parseStructCommonTypeQuestion(question) {
  const structType = question.type;
  let info = `${question.number}:${structType}`;
  const choiceQs = ["SINGLE_ANSWER_QUESTION", "MULTIPLE_ANSWER_QUESTION"];
  if (choiceQs.includes(structType)) {
    info += `:4`;
  } else if (structType === "FILL_BLANK_QUESTION") {
    info += `:1`;
  } else {
    info += ":";
  }

  return info;
}
