/* This is the script for popup-documents in Vivaldi */

/*eslint-disable no-undef*/

/* Can be a testbed for remotely rendered components */

let _theWebview;
let _addressField;
let _addressToolbar;

// vivaldiPopupContentId is set on the contentWindow in the document loading

function init() {
  _theWebview = document.createElement("webview");
  _theWebview.guestcontent_id = vivaldiPopupContentId;
  let webviewdiv = document.getElementById("webviewdiv");
  webviewdiv.appendChild(_theWebview);
  _addressField = document.getElementById("address-field");
  _addressToolbar = document.getElementById("main").
                      querySelector(".addressfield");
  attachWebViewListeners();
  // Resize the innersize with the height of the addressfield.
  let thisAppWindow = chrome.app.window.current();
  thisAppWindow.innerBounds.height +=
    (_addressToolbar.clientHeight + _addressToolbar.clientTop);
}

function attachWebViewListeners() {
  _theWebview.addEventListener("loadstart", updateAddressField);
  _theWebview.addEventListener("loadstop", updateTitle);
  _theWebview.addEventListener("sslstatechanged", updateSecurityState);
  _theWebview.addEventListener("newwindow", onNewWindow);
  _theWebview.addEventListener("close", onClose);
}

function onNewWindow(event) {
  event.window.accept(vivaldiWindowId + ";1");
}

function onClose(event) {
  let thisAppWindow = chrome.app.window.current();
  thisAppWindow.close();
}

function setupSiteInfoPopup() {
  let siteInfoElm =
      _addressToolbar.querySelector(".addressfield-siteinfo");
  if (siteInfoElm) {
    siteInfoElm.addEventListener(
      "click",
      function(event) {
        let buttonRect = event.currentTarget.getBoundingClientRect();
        let left = buttonRect.width;
        let titlebarHeight = window.outerHeight - window.innerHeight;
        _theWebview.showPageInfo({
          left: Math.floor(left + window.screenX),
          top: Math.floor(
            titlebarHeight + buttonRect.bottom + window.screenY)
        });
      }
    );
  }
}

function updateAddressField(event) {
  if (event.isTopLevel) {
    _addressField.value = event.url;
  }
}

function updateTitle() {
  _theWebview.executeScript({code: "document.title"}, result => {
    document.title = result ? result[0] : "";
  });
}

/*
function updateWindowIcon() {
  // TODO add api.
}*/

function updateSecurityState(event) {
  // Update the component based on the new security state.
  sendSiteInfoButtonUpdateRequest(event);
}

function sendSiteInfoButtonUpdateRequest(event) {

  const cType = "SiteInfoButton";
  const propsObj = {
    sslState: event.SSLState,
    isEditingUrl: false,
    sslIssuer: event.issuerstring,
    isInternal: false
  };

  // TODO: Check performance diff. of keeping a connection open with connect
  let payload = {renderComponentType: cType, props: propsObj};
  chrome.runtime.sendMessage(payload, function(response) {
    // Remove any old "addressfield-siteinfo" element before adding the updated
    // one.
    let oldSiteInfoElm =
        _addressToolbar.querySelector(".addressfield-siteinfo");
    if (oldSiteInfoElm) {
      oldSiteInfoElm.remove();
    }
    insertReadyComponent(_addressToolbar, response.result);

    // Attach the click handler on the inserted button.
    setupSiteInfoPopup();

  });
  }

function insertReadyComponent(parentElm, componentString) {
  parentElm.insertAdjacentHTML("afterbegin", componentString);
}

window.onload = init;
