import { Component, Prop, State, Event, Watch, h } from '@stencil/core';
import templates from './templates';
import { modalController, alertController } from '@ionic/core';
import { AuthStore } from '../../../stores/auth.store';
import userStore from '../../../stores/user.store';
import { StoreService } from "../../../services/store.service";
import { SignalRService } from '../../../services/signalR.service';
import signalRStore from '../../../stores/signalR.store';
export class SparklePage {
  constructor() {
    this.presentation = false;
    this.page = { title: null, path: null, body: null, pageInfo: null };
    this.isLesson = false;
    this.handleFacilitatorNavigationChange = (url) => {
      this.history.replace(url, {});
    };
    this.validateFetch = (response) => {
      if (!response.ok) {
        throw response;
      }
      return response.json();
    };
    this.handleNewPage = (page) => {
      this.badFetch = null;
      this.page = page;
      if (this.presentation) {
        this.page = Object.assign(Object.assign({}, this.page), { previousUrl: "/presentation" + this.page.previousUrl, nextUrl: "/presentation" + this.page.nextUrl });
      }
      StoreService.getInstance().UpdateTocPageInfo(this.page.pageInfo);
      this.isLesson = this.page.pageInfo.pageId > 0;
      this.pageDidLoad.emit({ pageInfo: this.page.pageInfo });
    };
    this.handleBadFetch = (error) => {
      this.badFetch = error;
      this.page = {
        title: error.statusText,
        body: null,
        path: null,
        pageInfo: null
      };
    };
  }
  componentWillLoad() {
    if (this.path) {
      return this.fetchPage(this.path);
    }
  }
  componentDidLoad() {
    if (this.presentation) {
      signalRStore.onChange("connected", (connected) => {
        if (connected) {
          SignalRService.getInstance().connection.on("NavigateFacilitatorPresentationCourseTo", this.handleFacilitatorNavigationChange);
        }
      });
    }
  }
  fetchPage(path, oldPath) {
    if (SignalRService.getInstance().connection.connectionState == "Connected") {
      SignalRService.getInstance().callSignalR("OnStudentNavigate", { url: window.location.href });
      if (this.presentation) {
        console.log('register listener');
        SignalRService.getInstance().connection.on("NavigateFacilitatorPresentationCourseTo", this.handleFacilitatorNavigationChange);
      }
    }
    if (path === null || path === oldPath) {
      return;
    }
    path = /^\/docs\/pages\/[a-z]{2}\.json$/.test(path) ? path.replace('.json', '/index.json') : path;
    return fetch(path).then(this.validateFetch).then(this.handleNewPage).catch(this.handleBadFetch);
  }
  disconnectedCallback() {
    StoreService.getInstance().UpdateTocPageInfo(null);
  }
  // @Watch('page')
  // setScrollPosition() {
  //   const hash = this.history.location.hash;
  //   if (this.isServer || (hash !== undefined && hash !== '')) {
  //     return;
  //   }
  //   requestAnimationFrame(() => {
  //     const { location } = this.history;
  //     const { scrollPosition = [0, 0] } = location;
  //     const [x, y] = scrollPosition;
  //     document.documentElement.scrollTo(x, y);
  //   });
  // }
  setDocumentMeta(page) {
    const { title, meta = {} } = page;
    const metaEls = {
      title: document.head.querySelectorAll('.meta-title'),
      description: document.head.querySelectorAll('.meta-description'),
      url: document.head.querySelectorAll('.meta-url, link[rel="canonical"]'),
      image: document.head.querySelectorAll('.meta-image'),
    };
    const updateMeta = (els, update) => {
      els.forEach((el) => {
        ['href', 'content'].forEach(attr => {
          if (el.hasAttribute(attr)) {
            el.setAttribute(attr, update(el.getAttribute(attr)));
          }
        });
      });
    };
    // Title
    const getTitle = () => {
      const suffix = /^\/docs\/pages\/appflow.*$/.test(this.path) ? 'Sparkle' : 'Sparkle';
      // Favor meta title, else go with auto-title. fallback to generic title
      return meta.title || title ? `${title} - ${suffix}` : suffix;
    };
    document.title = getTitle();
    updateMeta(metaEls.title, getTitle);
    // Canonical URL
    updateMeta(metaEls.url, (oldVal) => {
      const uri = '/docs/';
      const path = location.pathname.split(uri)[1];
      return oldVal.split(uri)[0] + uri + path;
    });
    // Description
    updateMeta(metaEls.description, () => meta.description || 'Sparkle is the free open-source platform for creating learning content on web, mobile and desktop.');
    // Sharing Image
    updateMeta(metaEls.image, () => meta.image || 'https://girlsinclearning.com//images/logo-primary.png');
  }
  hostData() {
    return {
      class: {
        [this.page.pageClass]: typeof this.page.pageClass === 'string',
      },
    };
  }
  async presentFeedbackModal() {
    const modal = await modalController.create({
      component: 'sparkle-feedback',
      cssClass: 'sparkle-modal sparkle-feedback-modal'
    });
    await modal.present();
  }
  async openProjectorPage() {
    if (userStore.state.user.FacilitatorClassList.length > 1) {
      await this.presentAlertClasses();
    }
    else {
      this.openWindows();
    }
  }
  async presentAlertClasses() {
    var inputs = [];
    //    var defaultCourseClassId = this.jwtService.getDefaultCourseClassId();
    var classes = userStore.state.user.FacilitatorClassList;
    classes.forEach((item, index) => inputs.push({
      name: 'radio' + index,
      type: 'radio',
      label: item.CourseName,
      value: item.CourseClassId,
      //checked: defaultCourseClassId > 0 ? item.CourseClassId == defaultCourseClassId : index == 0
    }));
    const alert = await alertController.create({
      header: 'Classes',
      inputs: inputs,
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
          }
        }, {
          text: 'Ok',
          handler: (data) => {
          }
        }
      ]
    });
    await alert.present();
  }
  openWindows() {
    //this.jwtService.updateDefaultCourseClassId(data);
    window.open(window.location.origin + "/presentation" + this.path.replace(".json", ""), "_blank");
    setTimeout(() => {
      window.open(window.location.origin + "/presentation" + '/teacher' + this.path.replace(".json", ""), "_blank");
    }, 500);
  }
  renderControls() {
    if (AuthStore.state.isAuthenticated) {
      return (h("div", { class: "controls" },
        h("ion-button", { onClick: () => this.presentFeedbackModal() },
          h("ion-icon", { name: "chatbox-outline" })),
        this.isLesson && userStore.state.user && userStore.state.user.Roles.indexOf('Facilitator') > -1 && h("ion-button", { onClick: () => this.openProjectorPage() },
          h("ion-icon", { name: "desktop-outline" }))));
    }
    return "";
  }
  render() {
    if (this.path) {
      const { page } = this;
      if (this.badFetch) {
        return templates.error(this.badFetch);
      }
      const Template = templates[page.template] || templates.default;
      const content = [
        h("main", { class: 'no-demo' },
          this.renderControls(),
          h(Template, { page: page }))
      ];
      return content;
    }
    else {
      return h("main", { class: 'no-demo' },
        h("slot", null));
    }
  }
  static get is() { return "sparkle-page"; }
  static get originalStyleUrls() { return {
    "$": ["page.css"]
  }; }
  static get styleUrls() { return {
    "$": ["page.css"]
  }; }
  static get properties() { return {
    "history": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "RouterHistory",
        "resolved": "RouterHistory",
        "references": {
          "RouterHistory": {
            "location": "import",
            "path": "@stencil/router"
          }
        }
      },
      "required": true,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "path": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": true,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "path",
      "reflect": false
    },
    "presentation": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "presentation",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "badFetch": {},
    "page": {},
    "isLesson": {}
  }; }
  static get events() { return [{
      "method": "pageDidLoad",
      "name": "pageDidLoad",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "{ pageInfo: IPageResult }",
        "resolved": "{ pageInfo: IPageResult; }",
        "references": {
          "IPageResult": {
            "location": "import",
            "path": "../../../models/page.model"
          }
        }
      }
    }]; }
  static get watchers() { return [{
      "propName": "path",
      "methodName": "fetchPage"
    }, {
      "propName": "page",
      "methodName": "setDocumentMeta"
    }]; }
}
