const contentDiv = document.getElementById("editor_block");
const titleButton = document.getElementById("title_button");
const submitButton = document.getElementById("submit_button");
contentApiUrl = `${PORTAL_SERVER}contents?url=${
  JSON.parse(document.getElementById("url").textContent).url
}`;

aa = "";
frontMatters = [];
contentMatters = [];
editorBlocks = [];
editorBlocks1 = [];
var editor;
var editorslider;
axios.get(contentApiUrl).then(({ data }) => {
  const content = data[0]["content"];
  var blockArray = [{ title: "", data: [] }];
  var blockCount = 0;
  blocks = parseMd(content);
  aa = new MDParser(content);
  editor_block = document.getElementById("editor_block");

  //ul = document.createElement('ul');
  //ul.id = "sortable";
  for (i = 0; i < blocks.length; i++) {
    //li = document.createElement('li');
    //odiv = document.createElement('div');
    //odiv.style.border = 'inset 1px gray';
    if (blocks[i]["text"].includes('br-tag')) {
      editorBlocks.push({
        type: "delimiter",
        data: { text: blocks[i]["text"] },
      });
    } else if (blocks[i]["type"] == "para") {
      editorBlocks.push({
        type: "paragraph",
        data: { text: blocks[i]["text"] },
      });
      //tmp = document.createElement('textarea');
      //tmp.style.border = 'outset 5px pink';
      //tmp.style.width = '100%';
      //tmp.value = blocks[i]['text'];
      //odiv.appendChild(tmp);
    } else if (blocks[i]["type"] == "br") {
      editorBlocks.push({ type: "paragraph", data: { text: "" } });
      //tmp = document.createElement('br');
      //odiv.appendChild(tmp);
    } else if (blocks[i]["type"] == "img") {
      ampimg = blocks[i]["text"];
      tmpsrc =
        BHOUSE_SERVER +
        JSON.parse(document.getElementById("url").textContent).url +
        "/" +
        ampimg.substr(
          ampimg.indexOf('src="') + 5,
          ampimg.indexOf('"', ampimg.indexOf('src="') + 5) -
            ampimg.indexOf('src="') -
            5
        );
      //tmpsrc = BHOUSE_SERVER + JSON.parse(document.getElementById('url').textContent).url + '/' + ampimg.substr(ampimg.indexOf("src=\"") + 5, ampimg.lastIndexOf(".") - ampimg.indexOf("src=\"") -1);
      //tmpsrc = ampimg.substr(ampimg.indexOf("src=\"") + 5, ampimg.indexOf(".webp") - ampimg.indexOf("src=\""));
      editorBlocks.push({
        type: "image",
        data: {
          file: {
            url: tmpsrc,
            width: parseInt(
              ampimg.substr(
                ampimg.indexOf('width="') + 7,
                ampimg.indexOf('"', ampimg.indexOf('width="') + 7) -
                  ampimg.indexOf('width="') -
                  7
              )
            ),
            height: parseInt(
              ampimg.substr(
                ampimg.indexOf('height="') + 8,
                ampimg.indexOf('"', ampimg.indexOf('height="') + 8) -
                  ampimg.indexOf('height="') -
                  8
              )
            ),
          },
          caption: ampimg
            .substr(
              ampimg.indexOf('alt="') + 5,
              ampimg.indexOf('"', ampimg.indexOf('alt="') + 5) -
                ampimg.indexOf('alt="') -
                5
            )
            .toString(),
          stretched: false,
          withBorder: true,
          withBackground: false,
        },
      });
      //img = document.createElement('img');
      //img.style.width = '100%';
      //img.src = tmpsrc;
      //odiv.appendChild(img);
    } else if (blocks[i]["type"] == "youtube") {
      ampimg = blocks[i]["text"];
      vid = ampimg.substr(
        ampimg.indexOf('data-videoid="') + 14,
        ampimg.indexOf('"', ampimg.indexOf('data-videoid="') + 14) -
          ampimg.indexOf('data-videoid="') -
          14
      );
      editorBlocks.push({
        type: "embed",
        data: {
          service: "youtube",
          source: "https://www.youtube.com/watch?" + vid,
          embed: "https://www.youtube.com/embed/" + vid,
          width: parseInt(
            ampimg.substr(
              ampimg.indexOf('width="') + 7,
              ampimg.indexOf('"', ampimg.indexOf('width="') + 7) -
                ampimg.indexOf('width="') -
                7
            )
          ),
          height: parseInt(
            ampimg.substr(
              ampimg.indexOf('height="') + 8,
              ampimg.indexOf('"', ampimg.indexOf('height="') + 8) -
                ampimg.indexOf('height="') -
                8
            )
          ),
        },
      });
    } else if (blocks[i]["type"] == "header1") {
      blocks[i]["text"] = blocks[i]["text"]
        .replace("### **", "")
        .replace("**", "");
      editorBlocks.push({
        type: "header",
        data: { level: 1, text: blocks[i]["text"] },
      });
    } else if (blocks[i]["type"] == "title") {
      blocks[i]["text"] = blocks[i]["text"]
        .replace("### **", "")
        .replace("**", "");
      editorBlocks.push({ type: "header", data: { text: blocks[i]["text"] } });
      //tmp = document.createElement('h3');
      //tmp.innerHTML = blocks[i]['text'];
      //odiv.appendChild(tmp);
    } else if (blocks[i]["type"] == "header3") {
      blocks[i]["text"] = blocks[i]["text"]
        .replace("### **", "")
        .replace("**", "");
      editorBlocks.push({
        type: "header",
        data: { level: 3, text: blocks[i]["text"] },
      });
    } else if (blocks[i]["type"] == "header4") {
      blocks[i]["text"] = blocks[i]["text"]
        .replace("### **", "")
        .replace("**", "");
      editorBlocks.push({
        type: "header",
        data: { level: 4, text: blocks[i]["text"] },
      });
    } else if (blocks[i]["type"] == "header5") {
      blocks[i]["text"] = blocks[i]["text"]
        .replace("### **", "")
        .replace("**", "");
      editorBlocks.push({
        type: "header",
        data: { level: 5, text: blocks[i]["text"] },
      });
    } else if (blocks[i]["type"] == "header6") {
      blocks[i]["text"] = blocks[i]["text"]
        .replace("### **", "")
        .replace("**", "");
      editorBlocks.push({
        type: "header",
        data: { level: 6, text: blocks[i]["text"] },
      });
    } else if (blocks[i]["type"] == "hr") {
      editorBlocks.push({ type: "paragraph", data: { text: "---" } });
    } else if (blocks[i]["type"] == "mt5") {
      editorBlocks.push({ type: "delimiter", data: {} });
    } else if (blocks[i]["type"] == "table") {
      editorBlocks.push({
        type: "table",
        data: { content: tableTextToArray(blocks[i]["text"]) },
      });
    }
    //li.appendChild(odiv);
    //ul.appendChild(li);
  }
  //editor_block.appendChild(ul);
  //$("#sortable").sortable();
  //$("#sortable").disableSelection();
  $("#editor_block").css({ display: "none" });
  $("#editorjs")[0].innerHTML = "";
  editor = new EditorJS({
    readOnly: false,
    holder: "editorjs",

    tools: {
      header: {
        class: Header,
        config: {
          placeholder: "Header",
        },
      },

      image: {
        class: ImageTool,
        inlineToolbar: ["link"],
        config: {
          endpoints: {
            byFile:
              "/backstage/upload" +
              JSON.parse(document.getElementById("url").textContent).url, // Your backend file uploader endpoint
            byUrl:
              "/backstage/getimage" +
              JSON.parse(document.getElementById("url").textContent).url, // Your endpoint that provides uploading by Url
            /* byFile: '/backstage/upload' + JSON.parse(document.getElementById('url').textContent).url.substring(JSON.parse(document.getElementById('url').textContent).url.lastIndexOf('/')), // Your backend file uploader endpoint
            byUrl: '/backstage/getimage' + JSON.parse(document.getElementById('url').textContent).url.substring(JSON.parse(document.getElementById('url').textContent).url.lastIndexOf('/')), // Your endpoint that provides uploading by Url */
            /* byFile: '/backstage/upload/' + $('#ctitle').val(), // Your backend file uploader endpoint
            byUrl: '/backstage/getimage/' + $('#ctitle').val(), // Your endpoint that provides uploading by Url */
          },
        },
      },
      // warning: {
      //   class: Warning,
      //   inlineToolbar: true,
      //   config: {
      //     titlePlaceholder: 'Title',
      //     messagePlaceholder: 'Message',
      //   },
      // },
      table: Table,
      delimiter: Delimiter,
      embed: Embed,
    },
    data: { blocks: editorBlocks },
  });
  if ($("#editorjs1").length > 0) {
    editorslider = new EditorJS({
      readOnly: false,
      holder: "editorjs1",
      tools: {
        paragraph: { inlineToolbar: false },
        image: {
          class: ImageTool,
          config: {
            endpoints: {
              byFile:
                "/backstage/upload" +
                JSON.parse(document.getElementById("url").textContent).url, // Your backend file uploader endpoint
              byUrl:
                "/backstage/getimage" +
                JSON.parse(document.getElementById("url").textContent).url, // Your endpoint that provides uploading by Url
              /* byFile: '/backstage/upload' + JSON.parse(document.getElementById('url').textContent).url.substring(JSON.parse(document.getElementById('url').textContent).url.lastIndexOf('/')), // Your backend file uploader endpoint
              byUrl: '/backstage/getimage' + JSON.parse(document.getElementById('url').textContent).url.substring(JSON.parse(document.getElementById('url').textContent).url.lastIndexOf('/')), // Your endpoint that provides uploading by Url */
              /* byFile: '/backstage/upload/' + $('#ctitle').val(), // Your backend file uploader endpoint
              byUrl: '/backstage/getimage/' + $('#ctitle').val(), // Your endpoint that provides uploading by Url */
            },
          },
        },
      },
      data: { blocks: editorBlocks1 },
    });
  }
  /*   for (var blockData of preBlockArray) {
      blockCount = loadDataToBlock(blockArray, blockCount, blockData);
    }
    titleButton.onclick = function () {
      blockCount = loadDataToBlock(blockArray, blockCount);
    } */
});

function editorSave() {
  if ($("#editorjs1").length > 0) {
    editor
      .save()
      .then((outputData) => {
        editorslider
          .save()
          .then((result) => {
            var articleinfo = GetMdHeader(result);
            var mdContent =
              '<div class="container-fluid blog_article p-0">\n\n';

            for (i = 0; i < outputData.blocks.length; i++) {
              var paragraphdata = "";

              block = outputData.blocks[i];
              if (block.type == "header") {
                let tag = "";
                switch (block.data.level) {
                  case 1:
                    tag = "# ";
                    break;
                  case 2:
                    tag = "## ";
                    break;
                  case 3:
                    tag = "### ";
                    break;
                  case 4:
                    tag = "#### ";
                    break;
                  case 5:
                    tag = "##### ";
                    break;
                  case 6:
                    tag = "###### ";
                    break;
                  default:
                    break;
                }
                mdContent += tag + block.data.text + "\n";
                // mdContent += `<h${block.data.level}>${block.data.text}</h${block.data.level}>`;
                // mdContent += "## " + block.data.text + "\n";
              } else if (block.type == "paragraph") {
                paragraphdata += block.data.text;

                if (paragraphdata != "") {
                  //make sure it's not empty
                  mdContent += paragraphdata + "\n\n";
                }
              } else if (block.type == "hr") {
                mdContent += "\n---\n";
              } else if (block.type == "image") {
                iurl = block.data.file.url.split("/");
                mdContent +=
                  '<img class="img-fluid" alt="' +
                  block.data.caption +
                  '"\n  src="' +
                  iurl[iurl.length - 2] +
                  "/" +
                  iurl[iurl.length - 1] +
                  '"\n  layout="responsive"></img>';
                if (block.data.caption != "") {
                  mdContent +=
                    '<div class="img-text">' + block.data.caption + "</div>";
                }
                mdContent += "\n\n";
              } else if (block.type == "delimiter") {
                mdContent += "\n---\n";
              } else if (block.type == "embed") {
                mdContent +=
                  "\n<iframe src=" +
                  block.data.embed.replace(
                    "https://www.youtube.com/embed/",
                    ""
                  ) +
                  'layout="responsive" width="' +
                  block.data.width +
                  '" height="' +
                  block.data.height +
                  '"></iframe>\n\n';
              } else if (block.type == "table") {
                mdContent +=
                  "\n" + tableArrayToHtml(block.data.content) + "\n\n";
              }
            }

            mdContent += "</div>\n\n";
            var mdData = articleinfo + "\n\n" + mdContent;

            postData = {
              content: mdData,
              url: JSON.parse(document.getElementById("url").textContent).url,
            };
            axios.post(contentApiUrl, (json = postData)).then(({ data }) => {
              alert("作品資料已儲存");
            });
          })
          .catch((error) => {
            console.log("Saving failed: ", error);
          });
      })
      .catch((error) => {
        console.log("Saving failed: ", error);
      });
  } else {
    editor
      .save()
      .then((outputData) => {
        //var articleinfo = frontMatters.join('\n');
        var articleinfo = GetMdHeader("editorSave");
        var mdContent = '<div class="container-fluid blog_article p-0">\n\n';
        //var headings = new Array();

        for (i = 0; i < outputData.blocks.length; i++) {
          var paragraphdata = "";

          block = outputData.blocks[i];
          if (block.type == "header") {
            let tag = "";
            switch (block.data.level) {
              case 1:
                tag = "# ";
                break;
              case 2:
                tag = "## ";
                break;
              case 3:
                tag = "### ";
                break;
              case 4:
                tag = "#### ";
                break;
              case 5:
                tag = "##### ";
                break;
              case 6:
                tag = "###### ";
                break;
              default:
                break;
            }
            mdContent += tag + block.data.text + "\n";
            // mdContent += "## " + block.data.text + "\n";
          } else if (block.type == "paragraph") {
            paragraphdata += block.data.text;

            if (paragraphdata != "") {
              //make sure it's not empty
              mdContent += paragraphdata + "\n\n";
            }
          } else if (block.type == "hr") {
            mdContent += "\n---\n";
          } else if (block.type == "image") {
            iurl = block.data.file.url.split("/");
            mdContent +=
              '<img class="img-fluid" alt="' +
              block.data.caption +
              '"\n  src="' +
              iurl[iurl.length - 2] +
              "/" +
              iurl[iurl.length - 1] +
              '"\n  layout="responsive"></img>';
            if (block.data.caption != "") {
              mdContent +=
                '<div class="img-text">' + block.data.caption + "</div>";
            }
            mdContent += "\n\n";
          } else if (block.type == "delimiter") {
            // mdContent += "\n---\n";
            // 放 <br> 會有跑版問題
            mdContent += "\n<span class='br-tag'></span>\n";
          } else if (block.type == "embed") {
            mdContent +=
              "\n<iframe src=" +
              block.data.embed.replace("https://www.youtube.com/embed/", "") +
              'layout="responsive" width="' +
              block.data.width +
              '" height="' +
              block.data.height +
              '"></iframe>\n\n';
          } else if (block.type == "table") {
            mdContent += "\n" + tableArrayToHtml(block.data.content) + "\n\n";
          }
        }

        var mdData = articleinfo + "\n\n" + mdContent;

        postData = {
          content: mdData,
          url: JSON.parse(document.getElementById("url").textContent).url,
        };
        axios.post(contentApiUrl, (json = postData)).then(({ data }) => {
          alert("作品資料已儲存");
        });
      })
      .catch((error) => {
        console.log("Saving failed: ", error);
      });
  }
}
submitButton.onclick = editorSave;
