var images = [];
var imagesRemove = [];
images = document.querySelector("#product_images").textContent.split(",");
var rmIL = $("#remove_imgs");
let productImagesObjects = [];

fetch("/admin/product/details/" + $("#product_id").val() + "?json=true").then(response => response.json()).then(function (res) {
  console.log(res);
  productImagesObjects = res.product.images;
});

function delete_p_img(e, imgPI) {
  let imgP = productImagesObjects[imgPI];
  imagesRemove.push(imgP);
  e.parentElement.remove();
  document.querySelector("#primaryImg").disabled = false;
  rmIL.val(JSON.stringify(imagesRemove));
}

function delete_s_img(e, imgPI) {
  let imgP = productImagesObjects[imgPI];
  imagesRemove.push(imgP);
  e.parentElement.remove();
  rmIL.val(JSON.stringify(imagesRemove));
}

/**************** Editor js */
const editor = new EditorJS();

editor.isReady
  .then(() => {
    var blocks = JSON.parse($("#description_blocks").val());
    editor.render({
      blocks
    });    /** Do anything you need after editor initialization */
  })
  .catch((reason) => {
    console.log(`Editor.js initialization failed because of ${reason}`)
  });

const edit_form = document.querySelector('#edit_form');
edit_form.addEventListener('submit', event => {
  event.preventDefault();
  // actual logic, e.g. validate the form
  save_description();
});

//save description
function save_description() {

  editor.save().then((output) => {
    console.log(output);
    var convertedHtml = "";
    output.blocks.map(block => {

      switch (block.type) {
        case "header":
          convertedHtml += `<h${block.data.level}>${block.data.text}</h${block.data.level}>`;
          break;
        case "embded":
          convertedHtml += `<div><iframe width="560" height="315" src="${block.data.embed}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></div>`;
          break;
        case "paragraph":
          convertedHtml += `<p>${block.data.text}</p>`;
          break;
        case "delimiter":
          convertedHtml += "<hr />";
          break;
        case "image":
          convertedHtml += `<img class="img-fluid" src="${block.data.file.url}" title="${block.data.caption}" /><br /><em>${block.data.caption}</em>`;
          break;
        case "list":
          convertedHtml += "<ul>";
          block.data.items.forEach(function (li) {
            convertedHtml += `<li>${li}</li>`;
          });
          convertedHtml += "</ul>";
          break;
        default:
          console.log("Unknown block type", block.type);
          break;
      }
    });
    $("#description_blocks").val(JSON.stringify(output.blocks));
    $("#productDesc").val(convertedHtml);
    document.getElementById("edit_form").submit();

  });
}