import { Component, Prop, State, Event, Watch, h } from '@stencil/core';
import templates from '../page/templates';
export class FacilitatorPage {
  constructor() {
    this.page = { title: null, path: null, body: null, pageInfo: null };
    this.validateFetch = (response) => {
      if (!response.ok) {
        throw response;
      }
      return response.json();
    };
    this.handleNewPage = (page) => {
      this.badFetch = null;
      this.page = page;
      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() {
    return this.fetchPage(this.path);
  }
  fetchPage(path, oldPath) {
    console.log("path", path);
    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);
  }
  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.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',
      },
    };
  }
  renderColumn2() {
    return (h("div", { class: "column-2" },
      h("div", null)));
  }
  renderColumn1(page) {
    const Template = templates[page.template] || templates.default;
    return (h("main", { class: 'no-demo column-1' },
      h(Template, { page: page })));
  }
  render() {
    const { page } = this;
    if (this.badFetch) {
      return templates.error(this.badFetch);
    }
    const content = [
      this.renderColumn1(page),
      this.renderColumn2()
    ];
    return 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
    }
  }; }
  static get states() { return {
    "badFetch": {},
    "page": {}
  }; }
  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"
    }]; }
}
