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

/**
 * Function for running a function until it completes successfully
 * with an optional delay between runs that gets progressively longer.
 *
 * Special Thanks to @MyBuilderTech
 * @see https://tech.mybuilder.com/handling-retries-and-back-off-attempts-with-javascript-promises/
 */
const pause = (duration) => new Promise((res) => setTimeout(res, duration));
async function backoff(retries, fn, delay = 500) {
  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);
        backoff(retries - 1, fn, delay * 2);
      }
      else {
        reject(err);
      }
    }
  });
}

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
let RenderTemplate = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.fireenjinFetch = createEvent(this, "fireenjinFetch", 7);
    this.data = {};
    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)
      backoff(10, this.renderTemplate.bind(this));
  }
  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 (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() {
    var _a, _b;
    this.html = lib.compile(((_a = this.template) === null || _a === void 0 ? void 0 : _a.html) ? (_b = this.template) === null || _b === void 0 ? void 0 : _b.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() {
    backoff(10, this.renderTemplate.bind(this));
  }
  onTemplate() {
    backoff(10, this.renderTemplate.bind(this));
  }
  render() {
    return h("div", { innerHTML: this.html || "" });
  }
  static get watchers() { return {
    "partials": ["setPartials"],
    "helpers": ["setHelpers"],
    "templateId": ["onTemplateId"],
    "data": ["onData"],
    "template": ["onTemplate"]
  }; }
};
__decorate([
  Debounce(1000)
], RenderTemplate.prototype, "setPartials", null);
__decorate([
  Debounce(1000)
], RenderTemplate.prototype, "setHelpers", null);

export { RenderTemplate as fireenjin_render_template };

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