import { Component, Prop, State, Event, Watch, h, Fragment } from '@stencil/core';
import { SignalRService } from '../../../services/signalR.service';
import templates from '../page/templates';
import { StoreService } from "../../../services/store.service";
import { TocStore } from '../../../stores/toc.store';
import { FacilitatorService } from '../../../services/facilitator.service';
import facilitatorStore from '../../../stores/facilitator.store';
export class FacilitatorPage {
  constructor() {
    this.isLesson = false;
    this.notesPage = { title: null, path: null, body: null, pageInfo: null };
    this.lessonNotesPage = { title: null, path: null, body: null, pageInfo: null };
    this.page = { title: null, path: null, body: null, pageInfo: null };
    this.onlineStudents = [];
    this.activetab = "FACILITATOR_NOTES";
    this.validateFetch = (response) => {
      if (!response.ok) {
        throw response;
      }
      return response.json();
    };
    this.handleNotesPage = (page) => {
      this.badFetch = null;
      this.notesPage = page;
      this.pageDidLoad.emit({ pageInfo: this.notesPage.pageInfo });
    };
    this.handleLessonNotesPage = (page) => {
      this.badFetchLessonNotes = null;
      this.lessonNotesPage = page;
    };
    this.handleNewPage = (page) => {
      this.page = page;
      this.page = Object.assign(Object.assign({}, this.page), { nextUrl: "/presentation/teacher" + this.page.nextUrl, previousUrl: "/presentation/teacher" + this.page.previousUrl });
      StoreService.getInstance().UpdateTocPageInfo(this.page.pageInfo);
    };
    this.handleBadFetch = (error) => {
      this.badFetch = error;
      this.notesPage = {
        title: error.statusText,
        body: null,
        path: null,
        pageInfo: null
      };
    };
    this.handleLessonNotesBadFetch = (error) => {
      this.badFetchLessonNotes = error;
      this.lessonNotesPage = {
        title: error.statusText,
        body: null,
        path: null,
        pageInfo: null
      };
    };
  }
  async componentWillLoad() {
    await this.fetchClasses();
    return this.fetchNotesPage(this.notesPath) && this.fetchPage(this.path);
  }
  componentDidLoad() {
    this.isLesson = TocStore.state.pageInfo.pageId > 0;
    if (!this.isLesson) {
      this.activetab = "ONLINE_STUDENTS";
    }
  }
  async fetchClasses() {
    await FacilitatorService.getInstance().fetchClasses();
  }
  fetchNotesPage(path, oldPath) {
    if (path === null || path === oldPath) {
      return;
    }
    path = /^\/docs\/pages\/[a-z]{2}\.json$/.test(path) ? path.replace('.json', '/index.json') : path;
    let lessonPath = this.getLessonPath(path);
    console.log(lessonPath);
    return fetch(path).then(this.validateFetch).then(this.handleNotesPage).catch(this.handleBadFetch) &&
      fetch(lessonPath).then(this.validateFetch).then(this.handleLessonNotesPage).catch(this.handleLessonNotesBadFetch);
  }
  getLessonPath(path) {
    let splittedPath = path.split("/");
    splittedPath.pop();
    return splittedPath.join("/") + "/lesson-notes.json";
  }
  fetchPage(path, oldPath) {
    if (path === null || path === oldPath) {
      return;
    }
    if (SignalRService.getInstance().connection.connectionState == "Connected") {
      SignalRService.getInstance().callSignalR("NavigateFacilitatorPresentationCourseTo", { url: this.path.replace(".json", "") });
    }
    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);
  }
  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.*$/.test(this.notesPath) ? '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.notesPage.pageClass]: typeof this.notesPage.pageClass === 'string',
      },
    };
  }
  renderNavigation() {
    return (h("div", { class: "p-2 d-md-flex justify-content-md-center" },
      h("div", { class: "btn-group btn-group-sm", role: "group", "aria-label": "Basic outlined example" },
        h("button", { type: "button", class: "btn btn-outline-primary" }, "Prev"),
        h("input", { type: "text", class: "form-control", placeholder: "Input group example", "aria-label": "Input group example", "aria-describedby": "btnGroupAddon", value: this.path.replace("index", ""), readOnly: true }),
        h("button", { type: "button", class: "btn btn-outline-primary" }, "Next"))));
  }
  renderTabs() {
    return (h("main", { class: 'no-demo' },
      h("ul", { class: "nav nav-tabs" },
        this.isLesson &&
          h(Fragment, null,
            h("li", { class: "nav-item" },
              h("a", { class: `nav-link ${this.activetab == "FACILITATOR_NOTES" ? 'active' : ''}`, href: "javascript:void(0)", onClick: () => this.activetab = "FACILITATOR_NOTES" }, "Facilitator Notes")),
            h("li", { class: "nav-item" },
              h("a", { class: `nav-link ${this.activetab == "NOTES" ? 'active' : ''}`, href: "javascript:void(0)", onClick: () => this.activetab = "NOTES" }, "Notes")),
            h("li", { class: "nav-item" },
              h("a", { class: `nav-link ${this.activetab == "LESSON_NOTES" ? 'active' : ''}`, href: "javascript:void(0)", onClick: () => this.activetab = "LESSON_NOTES" }, "Lesson Notes"))),
        h("li", { class: "nav-item" },
          h("a", { class: `nav-link ${this.activetab == "ONLINE_STUDENTS" ? 'active' : ''}`, href: "javascript:void(0)", onClick: () => this.activetab = "ONLINE_STUDENTS" }, "Online Students")),
        h("li", { class: "nav-item" },
          h("a", { class: `nav-link ${this.activetab == "DASHBOARD" ? 'active' : ''}`, href: "javascript:void(0)", onClick: () => this.activetab = "DASHBOARD" }, "Dashboard")),
        h("li", { class: "nav-item" },
          h("a", { class: `nav-link ${this.activetab == "EXPORT" ? 'active' : ''}`, href: "javascript:void(0)", onClick: () => this.activetab = "EXPORT" }, "Export"))),
      h("div", { class: "tab-content" },
        this.activetab == "FACILITATOR_NOTES" && this.renderFacilitatorNotes(),
        this.activetab == "NOTES" && h("sparkle-facilitator-notes", null),
        this.activetab == "LESSON_NOTES" && this.renderLessonNotes(),
        this.activetab == "ONLINE_STUDENTS" && h("sparkle-online-students", { path: this.path }),
        this.activetab == "DASHBOARD" && h("sparkle-facilitator-dashboard", null),
        this.activetab == "EXPORT" && h("sparkle-export-lessons", null))));
  }
  renderLessonNotes() {
    const { lessonNotesPage } = this;
    const Template = templates[lessonNotesPage.template] || templates.default;
    if (this.badFetchLessonNotes) {
      return templates.error(this.badFetch);
    }
    return h(Template, { page: lessonNotesPage });
  }
  renderFacilitatorNotes() {
    const { notesPage } = this;
    const Template = templates[notesPage.template] || templates.default;
    if (this.badFetch) {
      return templates.error(this.badFetch);
    }
    return h(Template, { page: notesPage });
  }
  render() {
    console.log(facilitatorStore.state.classes);
    const { page } = this;
    const content = this.renderTabs();
    return h("div", { class: "container" },
      h("div", { class: "d-flex justify-content-between align-items-center" },
        h("sparkle-page-footer", { page: page }),
        h("div", null,
          h("select", { class: "form-select", "aria-label": "Default select example" }, facilitatorStore.state.classes.map(item => h("option", null, item.ClassName))))),
      content);
  }
  static get is() { return "sparkle-facilitator-page"; }
  static get originalStyleUrls() { return {
    "$": ["facilitator-page.css"]
  }; }
  static get styleUrls() { return {
    "$": ["facilitator-page.css"]
  }; }
  static get properties() { return {
    "path": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": true,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "path",
      "reflect": false
    },
    "notesPath": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": true,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "notes-path",
      "reflect": false
    }
  }; }
  static get states() { return {
    "badFetch": {},
    "badFetchLessonNotes": {},
    "isLesson": {},
    "notesPage": {},
    "lessonNotesPage": {},
    "page": {},
    "onlineStudents": {},
    "activetab": {}
  }; }
  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": "notesPath",
      "methodName": "fetchNotesPage"
    }, {
      "propName": "path",
      "methodName": "fetchPage"
    }, {
      "propName": "page",
      "methodName": "setDocumentMeta"
    }]; }
}
