/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

window.onload = function () {
  /* The parent window hosts the Angular application */
  const parent = window.opener || window.parent; // opener for popup, parent for iframe
  /* Send the id_token information to the oidc message handler */
  const urlWithAuthorizationCode = window.location.href;

  // try to use session storage because events will not work if external identity provider is involved causing window.opener to be null (at least in firefox)
  if (localStorage) {
    // Hint: localStorage must be used, local storage will not work (no event received and no value set)
    localStorage.setItem('oidc-code-message', urlWithAuthorizationCode);
  }

  const event = new CustomEvent('oidc-code-message', {detail: urlWithAuthorizationCode});
  parent.dispatchEvent(event);

  document.getElementById('app-init-loader').classList.add('invisible');
  document.getElementById('app-info-message').classList.remove('invisible');

  // try to close popup; cannot check window.opener because that is null if external identity provider is involved (at least in firefox)
  // fails if window.opener is null (at least in firefox)
  setTimeout(function () {
    window.close();
  }, 100);
};
