import { getAnswerPointImg } from "./utils";
import { unix } from "moment";
import { AUDIO_IMG_URL } from "./constants";

let _isPreview = true;
// let _container;
/**
 * 将富文本 JSON 渲染到指定的元素中
 *
 * @param {RichTextJSON} body
 * @param {HTMLDivElement} container
 */
export function renderRichText(body, container, isPreview = true) {
  _isPreview = isPreview;
  // _container = container;
  let sections = body?.sections || [];
  let nodes = [];
  sections.forEach((section) => {
    nodes.push(renderSection(section));
  });
  if (container != undefined) {
    container.innerHTML = "";
    nodes.forEach((node) => {
      container.appendChild(node);
    });
  }
}

/**
 * @param {RichTextSectionJSON} section
 * @returns {HTMLDivElement} 返回根据 section 渲染好的 HTMLDivElement
 */
function renderSection(section) {
  let blocks = section.blocks || [];
  let inline = blocks.length > 1;
  let node = document.createElement("div");
  // node.style = "display: flex;";
  blocks.forEach((block) => {
    node.appendChild(renderBlock(block, inline));
  });
  return node;
}

/**
 * @param {RichTextBlockJSON} block
 * @param {Boolean} inline 图片是否以 inline 的样式展示
 * @returns {HTMLElement} 返回根据 block 渲染好的 HTMLElement
 */
function renderBlock(block, inline) {
  // let node = document.createElement('span')
  // let classList = node.classList
  let node;
  if (block.type === "text") {
    if (block.param) {
      let nodeNames = ["u", "b", "i", "sup", "sub"];
      let nodeParams = {
        u: "underline",
        b: "bold",
        i: "italic",
        sup: "sup",
        sub: "sub",
      };
      const nodes = nodeNames
        .filter((nodeName) => block.param[nodeParams[nodeName]])
        .map((nodeName) => {
          return document.createElement(nodeName);
        });

      nodes.push(document.createTextNode(block.value));
      // 将不为空的元素依次append
      node = nodes.reduceRight((p, c) => {
        c.appendChild(p);
        return c;
      });
    } else {
      node = document.createTextNode(block.value);
    }
  } else if (block.type === "image") {
    node = document.createElement("img");
    if (inline) node.classList.add("inline");

    node.src = block.value;
    node.dataset.isImage = true;
    // param
    if (block.param) {
      // 公式latex表达式
      if (block.param.latex) node.dataset.latex = block.param.latex;
      if (block.param.width) node.style.width = block.param.width + "px";
      if (block.param.height) node.style.height = block.param.height + "px";
    }
  } else if (block.type === "cloze") {
    node = document.createElement("img");
    node.src = getAnswerPointImg(block.value);
    node.dataset.isAnswerPoint = true;
    node.dataset.order = block.value;
  } else if (block.type === "audio") {
    // classList.add("audio");
    // let audio = node.appendChild(new Audio());
    // audio.src = block.value;
    // audio.controls = true;
    // span 可以被追加文本内容，不好
    // node = document.createElement("span");
    // node.className = "audio";
    // node.dataset["src"] = block.value;
    // node.innerHTML = "&#9654;";
    // // md5 src?
    // node.id = "what";
    // var sheet = window.document.styleSheets[0];
    // sheet.insertRule(
    //   `#what::after{content: "1:03"; font-size: 11px;}`,
    //   sheet.cssRules.length
    // );

    if (_isPreview) {
      node = document.createElement("audio");
      node.className = "audio";
      node.src = block.value;
      node.controls = true;
      node.controlsList = "nodownload";
    } else {
      node = document.createElement("img");
      node.className = "audio";
      node.src = AUDIO_IMG_URL;
      node.dataset.audioSrc = block.value;
      node.dataset.isAudio = true;
      if (block.param && block.param.duration) {
        node.dataset.duration = block.param.duration;
        const mDuration = unix(0);
        mDuration.second(block.param.duration);
        node.title = mDuration.format("mm:ss");
      }
    }
  }

  return node;
}
