import { Component, State, Event, Watch, Build, h } from '@stencil/core';
import { injectHistory } from '@stencil/router';
import { PrivateRoute } from '../../PrivateRoute';
import { AssetsService } from '../../services/core/assets.service';
import { AuthStore } from '../../stores/auth.store';
import { AuthService } from '../../services/auth/auth.service';
import { initSetupConfig as initSetupSparkleConfig } from '../../services/environment/environment-config';
import userStore from '../../stores/user.store';
export class SparkleCourseRoot {
  constructor() {
    this.history = null;
    this.tocPath = '/assets/content/toc.json';
    this.quizPath = '/assets/quiz.json';
    this.config = {
      appUrl: 'http://localhost:3333',
      globalAssetsUrl: 'http://localhost:3333/assets',
      apiUrl: 'https://localhost:44369/',
      quizPath: this.quizPath,
      tocPath: this.tocPath,
      menu: {
        showRomanNumber: true,
        showModuleIndex: true,
        showSessionIndex: true,
      },
      prod: true,
      courseId: 1,
    };
    this.isMenuToggled = false;
    //ICourse;
    this.setHistory = ({ history }) => {
      if (!this.history) {
        this.history = history;
        this.history.listen(this.newPage.bind(this));
      }
    };
    this.toggleMenu = () => {
      this.isMenuToggled = !this.isMenuToggled;
    };
    this.handlePageClick = () => {
      if (this.isSmallViewport() && this.isMenuToggled) {
        this.isMenuToggled = false;
      }
    };
  }
  newPage(location) {
    this.pageChanged.emit(location);
  }
  lockScroll(isMenuToggled) {
    if (Build.isBrowser && this.isSmallViewport()) {
      document.body.classList.toggle('scroll-lock', isMenuToggled);
    }
  }
  async componentWillLoad() {
    initSetupSparkleConfig({
      sparkle: Object.assign({}, this.config),
    });
    this.tocData = await AssetsService.getInstance().loadJsonFile(this.tocPath);
  }
  isSmallViewport() {
    return matchMedia && matchMedia('(max-width: 768px)').matches;
  }
  async toggleStudentSidebar() {
    var sidebar = document.getElementById('onlineStudents');
    await sidebar.show();
  }
  renderPage(path) {
    return (h("stencil-route", { url: '/' + path, routeRender: props => [
        this.renderHeaderAndMenu(),
        h("sparkle-page", { history: this.history, path: "" },
          path == 'login' && h("sparkle-login", null),
          path == 'signup' && h("sparkle-signup", { history: this.history }),
          path == 'forgot-password' && h("sparkle-forgot-password", { history: this.history }),
          path == 'reset-password' && h("sparkle-reset-password", { history: this.history })),
      ] }));
  }
  renderPrivatePage(path) {
    return (h(PrivateRoute, { url: '/' + path, render: () => [
        this.renderHeaderAndMenu(),
        h("sparkle-page", { history: this.history, path: "" },
          path == 'profile' && h("sparkle-user-profile", null),
          path == 'enrollment' && h("sparkle-user-enrollment", null),
          path == 'home/my-mood' && h("sparkle-mood", { history: this.history }),
          path == 'home/my-health' && h("sparkle-health", { history: this.history }),
          path == 'home/my-goals' && h("sparkle-goals", null),
          path == 'home/great-white-wall' && h("sparkle-gww", null)),
      ] }));
  }
  renderHeaderAndMenu() {
    return [this.renderHeader(), h("sparkle-menu", { toc: this.tocData, config: this.config.menu, toggleClickFn: this.toggleMenu })];
  }
  renderHeader() {
    return [
      h("sparkle-header", { courseName: this.tocData.name, toggleClickFn: this.toggleMenu, signoutClickFn: this.signout, authUser: AuthStore.state.isAuthenticated, imageUrl: userStore.state.user.ProfileImage }, this.renderLogo()),
    ];
  }
  async signout() {
    await AuthService.getInstance().signOut();
    this.history.replace('/login', {});
  }
  renderLogo() {
    return (h("a", { slot: "logo", href: "https://girlsinclearning.com/", target: "_blank" },
      h("img", { class: "girls-inc-logo", src: "/assets/img/logo-primary.png" })));
  }
  getFirstLessonUrl() {
    if (this.tocData) {
      let firstModule = this.tocData.courseModules[0];
      let firstSession = firstModule.sessions[0];
      let firstPage = firstSession.pages[0];
      let url = '/course/' + firstModule.urlName + '/' + firstSession.urlName + '/' + firstPage.urlName;
      return url;
    }
    else {
      return '/home';
    }
  }
  render() {
    const layout = {
      'Layout': true,
      'is-menu-toggled': this.isMenuToggled,
    };
    return (h("sparkle-root", { config: this.config },
      h("stencil-router", { class: layout },
        h("stencil-route", { style: { display: 'none' }, routeRender: this.setHistory }),
        h("stencil-route-switch", { scrollTopOffset: 0 },
          h("stencil-route", { url: "/", exact: true, routeRender: () => {
              return h("stencil-router-redirect", { url: this.getFirstLessonUrl() });
            } }),
          h("stencil-route", { url: "/unauthorized", routeRender: props => [this.renderHeaderAndMenu(), h("sparkle-unauthorized", null)] }),
          h("stencil-route", { url: "/course/:page*", routeRender: props => [
              this.renderHeaderAndMenu(),
              h("sparkle-page", { history: this.history, path: `/course/${props.match.params.page || 'index'}.json`, onClick: this.handlePageClick }),
            ] }),
          h("stencil-route", { url: "/presentation/course/:page*", routeRender: props => (h("sparkle-page", { history: this.history, presentation: true, path: `/course/${props.match.params.page || 'index'}.json`, onClick: this.handlePageClick })) }),
          h("stencil-route", { url: "/presentation/teacher/course/:page*", routeRender: props => [
              h("sparkle-facilitator-header", { courseName: this.tocData.name, toggleStudentClickFn: this.toggleStudentSidebar }, this.renderLogo()),
              h("sparkle-facilitator-page", { notesPath: `/course/${props.match.params.page || 'index'}-notes.json`, path: `/course/${props.match.params.page || 'index'}.json`, onClick: this.handlePageClick }),
            ] }),
          this.renderPrivatePage('home/my-mood'),
          this.renderPrivatePage('home/my-health'),
          this.renderPrivatePage('home/my-goals'),
          this.renderPrivatePage('home/great-white-wall'),
          h(PrivateRoute, { url: "/home/:page*", render: props => [
              this.renderHeaderAndMenu(),
              h("sparkle-page", { history: this.history, path: `/course/home/${props.match.params.page || 'index'}.json`, onClick: this.handlePageClick }),
            ] }),
          this.renderPage('login'),
          this.renderPage('signup'),
          this.renderPage('forgot-password'),
          this.renderPage('reset-password'),
          this.renderPrivatePage('profile'),
          this.renderPrivatePage('enrollment')))));
  }
  static get is() { return "sparkle-course-root"; }
  static get originalStyleUrls() { return {
    "$": ["sparkle-course-root.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sparkle-course-root.css"]
  }; }
  static get states() { return {
    "isMenuToggled": {},
    "tocData": {}
  }; }
  static get events() { return [{
      "method": "pageChanged",
      "name": "pageChanged",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get watchers() { return [{
      "propName": "isMenuToggled",
      "methodName": "lockScroll"
    }]; }
}
injectHistory(SparkleCourseRoot);
