require("./index.scss");

window.addEventListener("DOMContentLoaded", function () {
  let frameholder = document.getElementById("frameholder");
  let office_frame = document.createElement("iframe");
  office_frame.name = "office_frame";
  office_frame.id = "office_frame";

  // The title should be set for accessibility
  office_frame.title = "Office Frame";

  // This attribute allows true fullscreen mode in slideshow view
  // when using PowerPoint's 'view' action.
  office_frame.setAttribute("allowfullscreen", "true");

  // The sandbox attribute is needed to allow automatic redirection to the O365 sign-in page in the business user flow
  office_frame.setAttribute(
    "sandbox",
    "allow-downloads allow-scripts allow-same-origin allow-forms allow-modals allow-popups allow-top-navigation allow-popups-to-escape-sandbox",
  );
  frameholder.appendChild(office_frame);

  document.getElementById("office_form").submit();

  const url = new URL(editor_url);
  const editor_domain = url.origin;

  window.addEventListener("message", function (message) {
    if (message.origin !== editor_domain) {
      return;
    }

    let data = JSON.parse(message.data);

    if ("UI_Close" === data.MessageId) {
      closeEditor();
    }
  });
});

function closeEditor() {
  let params = new URLSearchParams(window.location.search),
    returnPath = params.get("returnPath");

  window.location.assign(returnPath);
}
