import '@flarehr/beacon';
import { Component, h, Host, Prop, State, Watch } from '@stencil/core';
import { injectHistory } from '@stencil/router';
import * as O from 'fp-ts/lib/Option';
import jwtDecode from 'jwt-decode';
import { Subscription } from 'rxjs';
import { getOrError } from '../../utils';
import { initIconsLibrary } from '../shared/icons-library';
import { BackendApiClient } from './apis/api-client';
import { renderManagePageRoutes } from './pages/manage-benefits-page/manage-benefits-page.routes';
import benefitsAppService, { BenefitsAppService } from './services/benefits-app.service';
import benefitsEventTrackingService from './services/event-tracking.service';
import navigationService from './services/navigation.service';
import benefitsAppQuery from './store/benefits-app.query';
export class BenefitsApp {
  constructor() {
    this.areStylesLoaded = false;
    this.storeSubscription = new Subscription();
  }
  async componentWillLoad() {
    const jwt = O.fromNullable(this.jwt);
    if (O.isNone(jwt)) {
      throw Error(`jwt property is missing.`);
    }
    const apiBaseUrl = O.fromNullable(this.apiBaseUrl);
    if (O.isNone(apiBaseUrl)) {
      throw Error(`apiBaseUrl property is missing.`);
    }
    const appBaseUrl = O.fromNullable(this.appBaseUrl);
    if (O.isNone(appBaseUrl)) {
      throw Error(`appBaseUrl property is missing.`);
    }
    const profileId = O.fromNullable(jwtDecode(jwt.value).sub);
    if (O.isNone(profileId)) {
      throw Error(`profileId property is missing.`);
    }
    const history = O.fromNullable(this.history);
    if (O.isNone(history)) {
      throw Error(`history property is missing.`);
    }
    navigationService.baseUrl = appBaseUrl.value;
    navigationService.history = history;
    BenefitsAppService.profileId = profileId.value;
    BackendApiClient.setParameters(apiBaseUrl.value, jwt.value);
    initIconsLibrary();
    await benefitsAppService.loadSignedInUserProfileAsync();
    this.storeSubscription.add(benefitsAppQuery.signedInUser$.subscribe((user) => {
      this.user = getOrError(user);
    }));
    this.storeSubscription.add(benefitsAppQuery.signedInUserRole$.subscribe((role) => {
      this.signedInUserRole = role;
    }));
  }
  disconnectedCallback() {
    this.storeSubscription.unsubscribe();
  }
  async componentDidLoad() {
    await benefitsEventTrackingService.trackAppLoadedAsync();
  }
  authTokenChanged(newValue) {
    if (this.apiBaseUrl === undefined) {
      throw 'Missing API base URL setting.';
    }
    BackendApiClient.setParameters(this.apiBaseUrl, newValue);
  }
  onRouteChange() {
    window === null || window === void 0 ? void 0 : window.scroll(0, 0);
  }
  render() {
    return (h(Host, { class: "d-flex flex-column justify-content-between" },
      this.fetchStyles(),
      this.areStylesLoaded && this.renderAppContent()));
  }
  fetchStyles() {
    return [
      h("link", { rel: "stylesheet", href: "https://npm-cdn.flarehr.com/@flarehr/beacon@dev/dist/beacon/beacon.css", media: "all", onLoad: () => (this.areStylesLoaded = true) })
    ];
  }
  routeUrl(route) {
    var _a, _b;
    return ((_b = (_a = this.appBaseUrl) === null || _a === void 0 ? void 0 : _a.replace(/\/$/, '')) !== null && _b !== void 0 ? _b : '') + route;
  }
  renderAppContent() {
    return (h("div", { class: "ap-ben-app-container d-flex flex-column" },
      h("div", { class: "container" },
        h("ap-ben-ui-container", { class: "d-none" },
          h("nav", { class: "navbar navbar-expand-lg navbar-light bg-white shadow-sm py-0" },
            h("stencil-route-link", { url: this.routeUrl('/'), exact: true, anchorClass: "nav-link", activeClass: "text-dark font-weight-bolder" }, "Home"),
            this.signedInUserRole !== 'user' && (h("stencil-route-link", { url: this.routeUrl('/manage'), anchorClass: "nav-link", activeClass: "text-dark font-weight-bolder" }, "Manage Benefits")),
            this.signedInUserRole === 'accountAdmin' && (h("stencil-route-link", { url: this.routeUrl('/admin'), anchorClass: "nav-link", activeClass: "text-dark font-weight-bolder" }, "Admin")),
            h("span", { class: "navbar-text pr-2 ml-auto" },
              "Welcome, ",
              this.user.basicProfile.firstName)))),
      h("div", { class: "container" },
        h("stencil-router", null,
          h("stencil-route-switch", { scrollTopOffset: 0 },
            h("stencil-route", { exact: true, url: this.routeUrl('/'), component: "ap-ben-benefits-page" }),
            renderManagePageRoutes(this.signedInUserRole, this.routeUrl(''))))),
      h("div", { class: "d-flex justify-content-center" },
        h("sss-footer-section", null))));
  }
  static get is() { return "benefits-app"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["benefits-app.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["benefits-app.css"]
  }; }
  static get properties() { return {
    "jwt": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "jwt",
      "reflect": false
    },
    "apiBaseUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "api-base-url",
      "reflect": false
    },
    "appBaseUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "app-base-url",
      "reflect": false
    },
    "location": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "LocationSegments",
        "resolved": "LocationSegments | undefined",
        "references": {
          "LocationSegments": {
            "location": "import",
            "path": "@stencil/router"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "history": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "RouterHistory",
        "resolved": "RouterHistory | undefined",
        "references": {
          "RouterHistory": {
            "location": "import",
            "path": "@stencil/router"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "areStylesLoaded": {},
    "user": {},
    "signedInUserRole": {}
  }; }
  static get watchers() { return [{
      "propName": "jwt",
      "methodName": "authTokenChanged"
    }, {
      "propName": "location",
      "methodName": "onRouteChange"
    }]; }
}
injectHistory(BenefitsApp);
