import { r as registerInstance, d as createEvent, B as Build, h, H as Host } from './index-33e43734.js';
import { l as lib } from './index-15dbcbaf.js';
import { l as logic } from './logic-2eecfe1e.js';
import './_commonjsHelpers-cca61ea8.js';

let RenderTemplate = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.fireenjinFetch = createEvent(this, "fireenjinFetch", 7);
    this.disableFrame = false;
    this.resize = false;
    this.zoom = 1;
    this.allowFullscreen = false;
    this.loading = "lazy";
    this.data = {};
    this.enableClicks = false;
    this.template = {};
    this.partials = [];
    this.helpers = {
      formatUSD: (amount) => {
        const formatter = new Intl.NumberFormat("en-US", {
          style: "currency",
          currency: "USD",
          minimumFractionDigits: 2,
        });
        return formatter.format(amount ? amount : 0);
      },
      logic: (context, rules, tempData) => logic.apply(JSON.parse(rules.replace('"@tempData"', tempData)), Object.assign(Object.assign({}, context), { tempData })),
    };
    this.html = "";
    this.currentPartials = [];
    this.currentHelpers = [];
  }
  async componentWillLoad() {
    var _a, _b;
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    if (this.helpers && ((_a = Object.keys(this.helpers)) === null || _a === void 0 ? void 0 : _a.length))
      this.setHelpers();
    if ((_b = this.partials) === null || _b === void 0 ? void 0 : _b.length)
      this.setPartials();
    if (this.templateId)
      this.getTemplate(this.templateId);
    if (this.template)
      this.backoff(10, this.renderTemplate.bind(this));
  }
  async componentDidLoad() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser) || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.html) || this.templateId)
      return;
    const templateHtml = (_e = (_d = (_c = (_b = this.templateSlot) === null || _b === void 0 ? void 0 : _b.assignedNodes) === null || _c === void 0 ? void 0 : _c.call(_b)) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.innerHTML;
    const dataStr = (_j = (_h = (_g = (_f = this.dataSlot) === null || _f === void 0 ? void 0 : _f.assignedNodes) === null || _g === void 0 ? void 0 : _g.call(_f)) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.innerHTML;
    if (dataStr) {
      try {
        this.data = JSON.parse(dataStr);
      }
      catch (e) {
        console.log("Error parsing JSON");
      }
    }
    this.renderTemplate(templateHtml);
  }
  async backoff(retries, fn, delay = 500) {
    const pause = (duration) => new Promise((res) => setTimeout(res, duration));
    return new Promise(async (resolve, reject) => {
      if (!fn || typeof fn !== "function")
        reject("Callback function is required!");
      try {
        const res = await fn();
        resolve(res);
      }
      catch (err) {
        if (retries > 1) {
          await pause(delay);
          this.backoff(retries - 1, fn, delay * 2);
        }
        else {
          reject(err);
        }
      }
    });
  }
  getBlobURL(code, type) {
    const blob = new Blob([code], { type });
    return URL.createObjectURL(blob);
  }
  getTemplate(id) {
    this.fireenjinFetch.emit({
      endpoint: "findTemplate",
      name: this.name,
      params: {
        id,
      },
    });
  }
  async fetchData(input) {
    this.getTemplate((input === null || input === void 0 ? void 0 : input.templateId) || this.templateId);
  }
  async unsetPartials() {
    for (const partialName of this.currentPartials) {
      lib.unregisterPartial(partialName);
    }
    this.currentPartials = [];
    this.partials = [];
  }
  async setPartials(partials) {
    try {
      lib.registerPartial(null, "");
    }
    catch (_a) {
      // Make sure handlebars doesn't error when null as partial name
    }
    try {
      if ((partials === null || partials === void 0 ? void 0 : partials.length) && this.partials !== partials) {
        this.partials = partials;
      }
      for (const partial of this.partials) {
        try {
          if (this.currentPartials.includes(partial === null || partial === void 0 ? void 0 : partial.id))
            lib.unregisterPartial(partial === null || partial === void 0 ? void 0 : partial.id);
          lib.registerPartial(partial === null || partial === void 0 ? void 0 : partial.id, (partial === null || partial === void 0 ? void 0 : partial.html) || "");
          if (!this.currentPartials.includes(partial === null || partial === void 0 ? void 0 : partial.id))
            this.currentPartials = [...this.currentPartials, partial === null || partial === void 0 ? void 0 : partial.id];
        }
        catch (_b) {
          console.log(`Error setting partial ${partial === null || partial === void 0 ? void 0 : partial.id}.`);
        }
      }
    }
    catch (_c) {
      console.log("Error setting partials.");
    }
  }
  async setHelpers(helpers) {
    try {
      if (helpers && this.helpers !== helpers) {
        this.helpers = helpers;
      }
      for (const [helperName, helperFn] of Object.entries(this.helpers)) {
        try {
          if (this.currentHelpers.includes(helperName))
            lib.unregisterHelper(helperName);
          lib.registerHelper(helperName, helperFn);
          if (!this.currentHelpers.includes(helperName))
            this.currentHelpers = [...this.currentHelpers, helperName];
        }
        catch (_a) {
          console.log(`Error setting helper ${helperName}.`);
        }
      }
    }
    catch (_b) {
      console.log("Error setting helpers.");
    }
  }
  async renderTemplate(html) {
    var _a;
    this.html = lib.compile(html || this.rawHtml || ((_a = this.template) === null || _a === void 0 ? void 0 : _a.html) || "")(this.data ? this.data : {});
  }
  onSuccess(event) {
    var _a, _b, _c, _d, _e, _f;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) === "findTemplate" &&
      ((_d = (_c = (_b = event.detail) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.template) === null || _d === void 0 ? void 0 : _d.id) === this.templateId) {
      this.template = ((_f = (_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.template)
        ? event.detail.data.template
        : null;
    }
  }
  onTemplateId() {
    this.fireenjinFetch.emit({
      endpoint: "findTemplate",
      params: {
        id: this.templateId,
      },
    });
  }
  onData() {
    this.backoff(10, this.renderTemplate.bind(this));
  }
  onTemplate() {
    this.backoff(10, this.renderTemplate.bind(this));
  }
  async fullscreen() {
    this.frameEl.requestFullscreen();
  }
  async getFrameEl() {
    return this.frameEl;
  }
  render() {
    const percentPosition = this.zoom && (1 / parseFloat(this.zoom)) * 100;
    return (h(Host, { style: {
        display: "block",
        resize: this.resize ? "both" : "initial",
        overflow: "auto",
      } }, h("div", { style: { display: "none" } }, h("slot", { ref: (el) => (this.templateSlot = el), name: "template" }), h("slot", { ref: (el) => (this.dataSlot = el), name: "data" })), h("div", { class: "render-wrapper", style: {
        position: "absolute",
        top: "0",
        left: "0",
        right: "0",
        bottom: "0",
        pointerEvents: this.enableClicks ? "initial" : "none",
      } }, this.disableFrame ? (h("div", { ref: (el) => (this.frameEl = el), style: {
        display: "block",
        transform: `scale(${this.zoom || 1})`,
        transformOrigin: "0 0",
        height: this.zoom ? `${percentPosition}%` : "100%",
        width: this.zoom ? `${percentPosition}%` : "100%",
      }, innerHTML: this.html })) : (h("iframe", { ref: (el) => (this.frameEl = el), style: {
        display: "block",
        transform: `scale(${this.zoom || 1})`,
        transformOrigin: "0 0",
        height: this.zoom ? `${percentPosition}%` : "100%",
        width: this.zoom ? `${percentPosition}%` : "100%",
      }, allowFullScreen: this.allowFullscreen, src: this.getBlobURL(this.html, "text/html"), frameBorder: 0, loading: this.loading }))), this.allowFullscreen && (h("ion-button", { style: {
        position: "absolute",
        top: "var(--fullscreen-button-top, 0px)",
        left: "var(--fullscreen-button-left, auto)",
        bottom: "var(--fullscreen-button-bottom, auto)",
        right: "var(--fullscreen-button-right, 0px)",
        "--background": "var(--fullscreen-button-background, transparent)",
        "--color": "var(--fullscreen-button-color, black)",
      }, fill: "clear", onClick: () => this.fullscreen() }, h("ion-icon", { style: {
        height: "var(--fullscreen-icon-size, 25px)",
        width: "var(--fullscreen-icon-size, 25px)",
      }, slot: "icon-only", name: "resize" })))));
  }
  static get watchers() { return {
    "partials": ["setPartials"],
    "helpers": ["setHelpers"],
    "templateId": ["onTemplateId"],
    "data": ["onData"],
    "template": ["onTemplate"]
  }; }
};

export { RenderTemplate as fireenjin_render_template };

//# sourceMappingURL=fireenjin-render-template.entry.js.map