import { getElementId, randomCode } from "../../plugins/utils";

const MODEL = {
  type: "FILL_LINE",
  x: 0,
  y: 0,
  w: 0,
  h: 40,
  minHeight: 40,
  sign: "subjective",
  topicName: "",
  topicNo: null,
  nameFontSize: "14px",
  nameFontWeight: 400,
  startNumber: 1,
  questionsCount: 4,
  questionNumberPerLine: 2,
  lineNumberPerQuestion: 1,
  lineSpacing: 40,
  questionDirection: "vertical",
  questionLineType: "norm",
  questionLineNums: [],
  numberPre: "",
  isCovered: false,
};

const getModel = (preSetData = {}) => {
  const model = Object.assign({}, MODEL, preSetData);

  return {
    id: getElementId(),
    key: randomCode(),
    ...model,
  };
};

const getFullModel = (model) => {
  const parent = { ...model };
  const numPerLine = model.questionNumberPerLine;
  let elements = [];

  let questionLineNums = model.questionLineNums;
  if (model.questionLineType === "norm") {
    questionLineNums = [];
    for (
      let j = model.startNumber;
      j < model.startNumber + model.questionsCount;
      j++
    ) {
      questionLineNums.push({
        no: j,
        count: model.lineNumberPerQuestion,
      });
    }
  }

  if (model.questionDirection === "vertical") {
    const total = Math.ceil(model.questionsCount / numPerLine);
    for (let i = 0; i < total; i++) {
      const childQuestionLineNums = questionLineNums.slice(
        i * numPerLine,
        (i + 1) * numPerLine
      );
      const maxLineNumberPerQuestion = Math.max.apply(
        null,
        childQuestionLineNums.map((item) => item.count)
      );
      const questionHeight = model.lineSpacing * maxLineNumberPerQuestion;
      let child = Object.assign({}, parent, {
        id: getElementId(),
        key: randomCode(),
        h: i ? questionHeight : questionHeight + 34,
        startNumber: model.startNumber + i * numPerLine,
        questionsCount:
          i === total - 1 ? model.questionsCount - numPerLine * i : numPerLine,
        parent: parent,
        isLast: i === total - 1,
        questionLineNums: childQuestionLineNums,
      });
      child.minHeight = child.h;

      elements[i] = child;
    }
  } else {
    for (let i = 0; i < model.questionsCount; i++) {
      const childQuestionLineNums = questionLineNums[i];
      const maxLineNumberPerQuestion = Math.ceil(
        childQuestionLineNums.count / numPerLine
      );
      const questionHeight = model.lineSpacing * maxLineNumberPerQuestion;
      let child = Object.assign({}, parent, {
        id: getElementId(),
        h: i ? questionHeight : questionHeight + 34,
        startNumber: model.startNumber + i,
        questionsCount: 1,
        parent: parent,
        isLast: i === model.questionsCount - 1,
        questionLineNums: [childQuestionLineNums],
      });
      child.minHeight = child.h;

      elements[i] = child;
    }
  }

  return elements;
};

export { MODEL, getModel, getFullModel };
