import { State, Component, Host, h } from '@stencil/core';
import { AssetsService } from '../../../../services';
import { EnvironmentConfigService } from "../../../../services/environment/environment-config.service";
import templates from '../../page/templates';
import jspdf from 'jspdf';
import html2canvas from 'html2canvas';
export class ExportLessons {
  constructor() {
    this.moduleContent = [];
    this.moduleName = "";
    this.page = { title: null, path: null, body: null, pageInfo: null };
    this.validateFetch = (response) => {
      if (!response.ok) {
        throw response;
      }
      return response.json();
    };
  }
  async fetchPage(path) {
    if (path === null) {
      return;
    }
    try {
      path = /^\/docs\/pages\/[a-z]{2}\.json$/.test(path) ? path.replace('.json', '/index.json') : path;
      const response = await fetch(path);
      return await this.validateFetch(response);
    }
    catch (e) {
      return {
        title: e.statusText,
        body: null,
        path: null,
        pageInfo: null
      };
    }
  }
  async getHTMLContent(path) {
    if (path) {
      let page = await this.fetchPage(path);
      if (!page.body) {
        console.log("Error while loading HTML content");
      }
      const Template = templates[page.template] || templates.pdf;
      const content = [
        h("main", { class: 'no-demo' },
          h(Template, { page: page }))
      ];
      return content;
    }
  }
  async componentWillLoad() {
    const sparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
    this.tocData = await AssetsService.getInstance().loadJsonFile(sparkleConfig.tocPath);
  }
  async renderContnet(courseModule) {
    this.moduleName = courseModule.name;
    let content = [];
    for (let i = 0; i < courseModule.sessions.length; i++) {
      for (let j = 0; j < courseModule.sessions[i].pages.length; j++) {
        const url = `/course/${courseModule.urlName}/${courseModule.sessions[i].urlName}/${courseModule.sessions[i].pages[j].urlName}.json`;
        content = [...content, await this.getHTMLContent(url)];
      }
    }
    this.moduleContent = [...content];
  }
  async exportToPDF() {
    var data = document.getElementById('exportPdf');
    html2canvas(data).then(canvas => {
      console.log(canvas);
      // Few necessary setting options    
      var imgWidth = 208;
      var pageHeight = 295;
      var imgHeight = canvas.height * imgWidth / canvas.width;
      var heightLeft = imgHeight;
      const contentDataURL = canvas.toDataURL('image/png');
      let pdf = new jspdf({ orientation: 'p', unit: "mm", format: "a4" });
      var position = 0;
      pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      pdf.save(this.moduleName + '.pdf');
    });
  }
  render() {
    return (h(Host, null,
      h("div", null, this.tocData.courseModules.map(item => h("div", { class: "p-2" },
        h("button", { class: "btn btn-primary", onClick: () => this.renderContnet(item) }, item.name)))),
      this.moduleContent.length > 0 && h("div", { class: "d-flex justify-content-end p-2" },
        h("button", { class: "btn btn-primary", onClick: () => this.exportToPDF() }, "Export to PDF")),
      h("div", { id: "exportPdf" }, this.moduleContent.map(item => item))));
  }
  static get is() { return "sparkle-export-lessons"; }
  static get originalStyleUrls() { return {
    "$": ["export-lessons.css"]
  }; }
  static get styleUrls() { return {
    "$": ["export-lessons.css"]
  }; }
  static get states() { return {
    "tocData": {},
    "moduleContent": {},
    "moduleName": {},
    "page": {}
  }; }
}
