export interface TextHtmlType {
  type: "img" | "text";
  value: string;
  bold?: boolean | undefined;
}

export const getTextHtml = (textHtmlArray: TextHtmlType[]) => {
  return `
    <meta charset="UTF-8">
    <article
      class="4ever-article"
      data-clipboard-cangjie="${getAsl(textHtmlArray)}"
    >
      ${getHTML(textHtmlArray)}
    </article>
  `;
};

const getAsl = (textHtmlArray: TextHtmlType[]) => {
  const asl = ["root", {}];

  asl.push(
    ...textHtmlArray.map(textHtml => {
      if (textHtml.type === "img") return getImgAsl(textHtml.value);
      return getTextAsl(textHtml.value, textHtml.bold);
    })
  );

  return JSON.stringify(asl).replace(/"/g, "&quot;");
};

const getHTML = (textHtmlArray: TextHtmlType[]) => {
  return textHtmlArray
    .map(textHtml => {
      if (textHtml.type === "img") return getImageHTML(textHtml.value);
      return getTextHTML(textHtml.value, textHtml.bold);
    })
    .join("");
};

const getImgAsl = (src: string) => {
  return [
    "p",
    {},
    ["span", { "data-type": "text" }, ["span", { "data-type": "leaf" }, ""]],
    [
      "img",
      {
        src,
      },
      ["span", { "data-type": "text" }, ["span", { "data-type": "leaf" }, ""]],
    ],
    ["span", { "data-type": "text" }, ["span", { "data-type": "leaf" }, ""]],
  ];
};

const getTextAsl = (text: string, bold: boolean | undefined) => {
  return [
    "p",
    {},
    ["span", { "data-type": "text" }, ["span", { "data-type": "leaf", bold: !!bold }, text]],
  ];
};

const getImageHTML = (src: string) => `
  <p>
    <span data-type="text"></span>
    <img src="${src}" >
    <span data-type="text"></span>
  </p>
`;

const getTextHTML = (text: string, bold: boolean | undefined) => `
  <p>
    <span data-type="text" ${bold ? 'style="font-weight: bold"' : ""}>${text}</span>
  </p>
`;
