const { toJSON } = require("../toJSON");

let bToSource = false;
let bToJSON = false;

/**
 *
 * @param {string} type
 * @param {HTMLDivElement} edt
 */
export function setDocMode(type, edt) {
  if (type === "HTML") {
    // if (bToSource === true) return;
    bToJSON = false;
    bToSource = !bToSource;
  }
  if (type === "JSON") {
    if (bToSource === true) return;
    bToSource = false;
    bToJSON = !bToJSON;
  }

  let oContent;
  if (bToSource) {
    oContent = document.createTextNode(edt.innerHTML);
    edt.innerHTML = "";
    edt.contentEditable = false;
    let oPre = document.createElement("pre");

    oPre.className = "sourceView";
    oPre.contentEditable = true;
    oPre.style = "overflow: scroll; white-space: normal;";
    oPre.appendChild(oContent);
    edt.appendChild(oPre);
    // 似乎chrome不支持将默认分段改为p
    document.execCommand("defaultParagraphSeparator", false, "div");
  } else if (bToJSON) {
    const je = document.createElement("div");
    je.style =
      "position: absolute; top: 0; left: 0; background: beige; width: 100%; padding: 5px; z-index: 1000000";

    oContent = document.createTextNode(toJSON(edt));

    let oPre = document.createElement("pre");

    // oPre.className = "sourceView";
    edt.contentEditable = false;
    oPre.style = "overflow: scroll;";
    oPre.appendChild(oContent);
    oPre.innerHTML = "双击关闭\n\n\n" + oPre.innerHTML;
    je.appendChild(oPre);
    document.body.appendChild(je);

    je.addEventListener("dblclick", () => {
      document.body.removeChild(je);
      bToJSON = false;
      edt.contentEditable = true;
    });
  } else {
    oContent = document.createRange();
    oContent.selectNodeContents(edt.firstChild);
    edt.innerHTML = oContent.toString();
    edt.contentEditable = true;
  }
  edt.focus();
}
