// const _text_styles_ = ["bold", "underline", "italic", "sup", "sub"];

export function renderRichText(body, container) {
  let sections = body?.sections || [];
  let nodes = [];
  sections.forEach((section) => {
    nodes.push(renderSection(section));
  });
  if (container != undefined) {
    // container.classList.add("rich-text");
    while (container.hasChildNodes()) {
      container.removeChild(container.lastChild);
    }
    nodes.forEach((node) => {
      container.appendChild(node);
    });
  }

  return nodes;
}

function renderSection(section) {
  let blocks = section.blocks || [];
  let inline = blocks.length > 1;
  let node = document.createElement("div");
  blocks.forEach((block) => {
    node.appendChild(renderBlock(block, inline));
  });
  return node;
}

function renderBlock(block, inline) {
  // let node = document.createElement('span')
  // let classList = node.classList
  let node;
  if (block.type === "text") {
    // classList.add('text')
    // if (block.param != undefined) {
    //     _text_styles_.forEach(style => {
    //         if (block.param[style] === true) {
    //             classList.add(style)
    //         }
    //     })
    // }
    if (block.param) {
      let uNode, bNode, iNode;
      if (block.param.underline) {
        uNode = document.createElement("u");
      }
      if (block.param.bold) {
        bNode = document.createElement("b");
      }
      if (block.param.italic) {
        iNode = document.createElement("i");
      }
      // 将不为空的元素依次append
      node = [uNode, bNode, iNode]
        .filter((v) => v)
        .reduceRight((p, c) => {
          c.appendChild(p);
          return c;
        });

      let childNode = node;

      for (let i = 0; i < 3; i++) {
        if (childNode && childNode.hasChildNodes()) {
          childNode = childNode.childNodes[0];
        }
      }

      childNode.textContent = block.value;
    } else {
      node = document.createTextNode(block.value);
    }
  } else if (block.type === "image") {
    // classList.add("image");
    // classList.add("loading");
    node = document.createElement("img");
    if (inline === true) {
      node.classList.add("inline");
    }
    node.src = block.value;
    // img.onload = function () {
    //   this.parentNode.classList.remove("loading");
    // };
  } else if (block.type === "audio") {
    // classList.add("audio");
    // let audio = node.appendChild(new Audio());
    // audio.src = block.value;
    // audio.controls = true;
  }

  return node;
}
