import { Component, Host, h, Prop } from '@stencil/core';
import { setupConfig as setupSparkleConfig } from '../../services/environment/environment-config';
import { HttpService } from '../../services/httpService';
import { StudentService } from '../../services/student.service';
import { EnvironmentConfigService } from '../../services/environment/environment-config.service';
import { AuthStore } from "../../stores/auth.store";
import { SignalRService } from '../../services/signalR.service';
import { injectHistory } from '@stencil/router';
export class SparkleRoot {
  constructor() {
    this.history = null;
    this.handleStudentNavigationChange = (url) => {
      this.history.replace(url, {});
    };
  }
  async componentWillLoad() {
    setupSparkleConfig({
      sparkle: Object.assign(Object.assign({}, this.config), { prod: true })
    });
    //return Promise.reject();
    await HttpService.getInstance();
    await HttpService.init();
    var sparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
    if (sparkleConfig && sparkleConfig.auth && sparkleConfig.auth.getToken()) {
      AuthStore.state.isAuthenticated = true;
    }
    ;
    AuthStore.onChange("isAuthenticated", async (isAuthenticated) => {
      if (isAuthenticated) {
        console.log('authenticated');
        await StudentService.getInstance().fetchUserConfiguration();
      }
    });
    if (AuthStore.state.isAuthenticated) {
      return await StudentService.getInstance().fetchUserConfiguration();
    }
    //SignalRAspNetCoreHelper.initSignalR();
  }
  componentDidLoad() {
    SignalRService.getInstance().connection.on("NavigateStudentTo", this.handleStudentNavigationChange);
    AuthStore.onChange("isAuthenticated", async (isAuthenticated) => {
      if (isAuthenticated) {
        SignalRService.getInstance().start();
      }
    });
    if (AuthStore.state.isAuthenticated) {
      SignalRService.getInstance().start();
    }
  }
  render() {
    return (h(Host, null,
      h("slot", null)));
  }
  static get is() { return "sparkle-root"; }
  static get originalStyleUrls() { return {
    "$": ["sparkle-root.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sparkle-root.css"]
  }; }
  static get properties() { return {
    "config": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "EnvironmentSparkleConfig",
        "resolved": "EnvironmentSparkleConfig",
        "references": {
          "EnvironmentSparkleConfig": {
            "location": "import",
            "path": "../../services/environment/environment-config"
          }
        }
      },
      "required": true,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
}
injectHistory(SparkleRoot);
