const Penpal = require("penpal").default;

/**
 * Sets up interaction with Vereign Restful API
 * @param divId - target container to append iframe via Penpal
 * @param methods - list of methods to be used in iframe
 * @param iframeUrl - iframe URL to connect
 * @param apiUrl -  API URL used to access API endpoints
 * @param wopiUrl -  WOPI URL used to acces WopiAPI
 * @returns {*}
 */
function setupViamAPI(
  divId,
  methods,
  iframeUrl,
  apiUrl,
  wopiUrl,
  collaboraUrl
) {
  if (!iframeUrl) {
    iframeUrl = `${window.location.origin}/vcl/js/iframe`;
    console.warn(`Iframe URL not specified. Fall back to ${iframeUrl}`); // eslint-disable-line no-console
  }

  const connection = Penpal.connectToChild({
    // URL of page to load into iframe.
    url: iframeUrl,
    // Container to which the iframe should be appended.
    appendTo: document.getElementById(divId),
    // Methods parent is exposing to child
    methods
  });

  return connection.promise.then(child =>
    child.initialize(apiUrl, wopiUrl, collaboraUrl).then(() => child)
  );
}

window.setupViamAPI = setupViamAPI;