import '@flarehr/beacon';
import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer';
import { Component, h, Host, State } from '@stencil/core';
import * as O from 'fp-ts/lib/Option';
import iframe from '../../utils/iframe';
import { buildOidcStencilRoutes } from './oidc-callback-page/oidc-callback-page.routes';
import appConfigurationQuery from './services/app-configuration.query';
import appConfigurationService from './services/app-configuration.service';
import sessionQuery from './services/authentication.query';
import oidcService from './services/authentication.service';
import { AuthenticationState } from './services/session.store';
export class SuperSelectionAppHost {
  async componentWillLoad() {
    await appConfigurationService.loadConfigurationAsync(`${appConfigurationService.getAppHostUrl()}/static/config.json`);
    if (sessionQuery.isUnauthorized || oidcService.shouldPerformSignIn(window.location.search)) {
      oidcService.initFromRoute(window.location.pathname, window.location.search);
    }
    sessionQuery.sessionState$.subscribe((updatedState) => (this.sessionState = updatedState));
    sessionQuery.jwt$.subscribe((newToken) => (this.jwt = newToken));
    appConfigurationQuery.appConfiguration$.subscribe((updatedConfiguration) => (this.appConfiguration = updatedConfiguration));
  }
  render() {
    if (O.isNone(this.appConfiguration))
      return h("ap-ben-loading-page", null);
    const appBaseUrl = appConfigurationService.getAppRootUrl(false);
    return (h(Host, { class: "w-100" },
      h("stencil-router", null,
        h("stencil-route-switch", { scrollTopOffset: 0 },
          buildOidcStencilRoutes(),
          h("stencil-route", { url: appBaseUrl, routeRender: this.renderProtectedRoute((props) => (h("benefits-app", Object.assign({ ref: (el) => this.observeContentResize(el), jwt: O.toUndefined(this.jwt), apiBaseUrl: appConfigurationQuery.configuration.ApiBaseUrl, appBaseUrl: appBaseUrl }, props)))) })))));
  }
  renderProtectedRoute(renderProtectedComponent) {
    switch (this.sessionState) {
      case AuthenticationState.Authenticated:
        return renderProtectedComponent;
      case AuthenticationState.Unauthorized:
      case AuthenticationState.SignOutPending:
      case AuthenticationState.SignInPending:
        return () => h("ap-ben-loading-page", null);
      case AuthenticationState.Error:
        return () => h("h1", null, "Authentication Error");
    }
  }
  observeContentResize(appContent) {
    const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill;
    new ResizeObserver(() => {
      iframe.resize(appContent.offsetHeight, -1);
    }).observe(appContent);
  }
  static get is() { return "benefits-app-host"; }
  static get states() { return {
    "sessionState": {},
    "jwt": {},
    "appConfiguration": {}
  }; }
}
