'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-e0385008.js');
const hardwareBackButton = require('./overlays-83fe75fb.js');
const moveItemInArray = require('./moveItemInArray-a7d656ab.js');
require('./ionic-global-45d4a7f7.js');
require('./helpers-905b0d22.js');

const appFlowCss = "";

const AppFlow = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.fireenjinFetch = index.createEvent(this, "fireenjinFetch", 7);
    this.fireenjinSubmit = index.createEvent(this, "fireenjinSubmit", 7);
    this.fireenjinTrigger = index.createEvent(this, "fireenjinTrigger", 7);
    this.stepInput = {};
    this.showCode = false;
    this.flowId = undefined;
    this.stepId = undefined;
    this.db = undefined;
    this.flow = {};
    this.step = {};
    this.steps = [];
    this.showCodeInputForStep = {};
    this.toggleSteps = false;
    this.toggleFields = false;
    this.field = undefined;
  }
  onSubmit(event) {
    var _a, _b;
    if (((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "addPathForm") {
      this.addToPath(event.detail.data.path, event.detail.data.steps);
      this.formEl.submit();
    }
    else if (((_b = event === null || event === void 0 ? void 0 : event.target) === null || _b === void 0 ? void 0 : _b.name) === "addFieldForm") {
      this.field = event.detail.data.field;
      this.addFieldToStep(this.field);
      this.stepFormEl.submit();
      this.fieldEl.value = null;
    }
  }
  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) === "listSteps") {
      this.steps = ((_c = (_b = event === null || event === void 0 ? void 0 : event.detail) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.steps) || [];
    }
    else if (((_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.endpoint) == "findFlow") {
      this.flow = ((_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.flow) || {};
    }
    else {
      this.pathNameInputEl.value = null;
      this.stepsSelectEl.value = null;
    }
  }
  async onReorder(event) {
    console.log(event);
    this.flow.paths[event.target.dataset.path] = moveItemInArray.moveItemInArray(this.flow.paths[event.target.dataset.path], event.detail.from, event.detail.to);
    event.detail.complete();
    this.formEl.submit();
  }
  async openUserSearch() {
    this.modalEl = await hardwareBackButton.modalController.create({
      cssClass: "modal-search-users",
      component: "modal-search-users",
      componentProps: {
        flow: this === null || this === void 0 ? void 0 : this.flow,
      },
    });
    this.modalEl.present();
  }
  async fetchSteps() {
    this.fireenjinFetch.emit({
      endpoint: "listSteps",
    });
  }
  async getData() {
    this.fireenjinTrigger.emit({
      name: "subscribe",
      payload: {
        collection: "flows",
        id: this.flowId,
        callback: ({ data }) => {
          this.flow = data;
        },
      },
    });
    await this.fetchSteps();
  }
  disconnectedCallback() {
    this.fireenjinTrigger.emit({
      name: "unsubscribe",
      payload: {
        collection: "flows",
        id: this.flowId,
      },
    });
  }
  /**
   * Simple object check.
   * @param item
   * @returns {boolean}
   */
  isObject(item) {
    return item && typeof item === "object" && !Array.isArray(item);
  }
  /**
   * Deep merge two objects.
   * @param target
   * @param ...sources
   */
  mergeDeep(target, ...sources) {
    if (!sources.length)
      return target;
    const source = sources.shift();
    if (this.isObject(target) && this.isObject(source)) {
      for (const key in source) {
        if (this.isObject(source[key])) {
          if (!target[key])
            Object.assign(target, { [key]: {} });
          this.mergeDeep(target[key], source[key]);
        }
        else {
          Object.assign(target, { [key]: source[key] });
        }
      }
    }
    return this.mergeDeep(target, ...sources);
  }
  async openCodeEditor(name, value = "{}") {
    console.log(name, value);
    const modalEl = await hardwareBackButton.modalController.create({
      component: "fireenjin-mx-modal-code-editor",
      cssClass: "fireenjin-mx-modal-code-editor-wrapper",
      componentProps: {
        pageTitle: "Edit Step Input",
        name,
        language: "json",
        value: JSON.stringify(value),
        endpoint: "editFlow",
        documentId: this.flowId,
        beforeSubmit: (data) => {
          return this.mergeDeep(this.flow, data);
        },
      },
    });
    await modalEl.present();
    return modalEl;
  }
  showSteps() {
    this.toggleSteps = !this.toggleSteps;
  }
  showFields() {
    this.toggleFields = !this.toggleFields;
  }
  stepSelect(step) {
    this.stepId = step.id;
    this.step = step;
    this.showSteps();
  }
  fieldSelect(field) {
    this.field = field;
    this.showFields();
  }
  addFieldToStep(field) {
    if (!this.step.fields)
      this.step.fields = [];
    this.step.fields.push(field);
  }
  addToPath(path, steps) {
    var _a, _b, _c, _d;
    if (!this.flow.paths)
      this.flow.paths = {};
    if (!this.flow.paths[path])
      this.flow.paths[path] = [];
    for (const stepId of steps) {
      (_d = (_c = (_b = (_a = this.flow) === null || _a === void 0 ? void 0 : _a.paths) === null || _b === void 0 ? void 0 : _b[path]) === null || _c === void 0 ? void 0 : _c.push) === null || _d === void 0 ? void 0 : _d.call(_c, {
        step: this.db.document("steps", stepId),
        input: {},
      });
    }
    this.flow = { ...this.flow };
  }
  componentDidLoad() {
    if (!(index.Build === null || index.Build === void 0 ? void 0 : index.Build.isBrowser))
      return;
    this.getData();
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    const stepOptions = this.steps.map((step) => ({
      label: (step === null || step === void 0 ? void 0 : step.name) || "no name",
      value: step === null || step === void 0 ? void 0 : step.id,
    }));
    return [
      index.h("ion-content", null, index.h("floodteam-title-bar", null, index.h("ion-router-link", { href: "/flows" }, "Flows"), index.h("ion-buttons", { slot: "end" }, index.h("ion-button", { fill: "solid", color: "primary", href: "/flows/new" }, "Add"))), index.h("ion-grid", null, index.h("ion-row", null, index.h("ion-col", null, index.h("fireenjin-form", { hideControls: true, ref: (el) => (this.formEl = el), endpoint: this.flowId === "new" ? "addFlow" : "editFlow", documentId: this.flowId, formData: this.flow }, index.h("ion-card", null, index.h("ion-grid", null, index.h("ion-row", null, index.h("ion-col", { "size-sm": "9", size: "12" }, index.h("fireenjin-input", { "data-fill": true, name: "name", label: "Name", "label-position": "stacked", value: (_a = this.flow) === null || _a === void 0 ? void 0 : _a.name })), index.h("ion-col", { "size-sm": "3", size: "12" }, index.h("fireenjin-toggle", { value: (_b = this.flow) === null || _b === void 0 ? void 0 : _b.showProgress, "data-fill": true, color: "primary", lines: "none", label: "Show Progress", labelPosition: "stacked", name: "showProgress" })))), index.h("fireenjin-select-tags", { name: "tags", "data-fill": true, labelPosition: "stacked", label: "Tags", value: ((_c = this.flow) === null || _c === void 0 ? void 0 : _c.tags) || [], allowAdding: true, options: [
          {
            label: "Important",
            value: "important",
          },
        ] })), index.h("ion-card", null, index.h("ion-item-divider", null, "Add Users"), index.h("floodteam-title-bar", { heading: 4, disableUnderline: true, icon: "people" }, index.h("ion-text", null, "Users"), index.h("ion-button", { fill: "outline", href: "#", slot: "end", size: "small", onClick: () => this.openUserSearch() }, "Add"))), index.h("ion-card", null, index.h("ion-item", { class: "json-editor-field", style: { zIndex: "3" } }, index.h("ion-label", null, index.h("h2", null, "Success Message"), index.h("fireenjin-code-editor", { autoExpand: true, value: ((_d = this.flow) === null || _d === void 0 ? void 0 : _d.successTemplate) || "", language: "html", name: "successTemplate", "data-fill": true }))), index.h("ion-item", { class: "json-editor-field", style: { zIndex: "3" } }, index.h("ion-label", null, index.h("h2", null, "Error Message"), index.h("fireenjin-code-editor", { "data-fill": true, autoExpand: true, value: ((_e = this.flow) === null || _e === void 0 ? void 0 : _e.errorTemplate) || "", language: "html", name: "errorTemplate" }))))), index.h("ion-card", null, index.h("ion-item-divider", null, "Paths"), index.h("ion-grid", null, index.h("ion-row", null, index.h("ion-col", null, index.h("ion-accordion-group", null, Object.entries(((_f = this.flow) === null || _f === void 0 ? void 0 : _f.paths) || {}).map(([pathName, steps]) => (index.h("ion-accordion", null, index.h("ion-item", { slot: "header" }, index.h("ion-label", null, pathName || "name")), index.h("ion-reorder-group", { "data-path": pathName, disabled: false, slot: "content" }, (steps || []).map(({ step, input }, index$1) => {
        var _a;
        return (index.h("ion-item", null, index.h("ion-label", null, ((_a = (this.steps || []).find((s) => s.id === step.id)) === null || _a === void 0 ? void 0 : _a.name) || "no step"), index.h("div", { slot: "end", style: { display: "flex" } }, index.h("ion-button", { fill: (input === null || input === void 0 ? void 0 : input.length) && input !== "{}"
            ? "solid"
            : "outline", onClick: () => this.openCodeEditor(`paths.${pathName}[${index$1}].input`, input) }, "Input"), index.h("ion-reorder", null))));
      }))))))))), index.h("ion-item-divider", null, "Add Path"), index.h("fireenjin-form", { name: "addPathForm", disableLoader: true, submitButton: "Add", resetButton: null }, index.h("ion-grid", null, index.h("ion-row", null, index.h("ion-col", { "size-sm": "4", size: "12" }, index.h("fireenjin-input", { ref: (el) => (this.pathNameInputEl = el), name: "path", "data-fill": true, label: "Name", labelPosition: "stacked" })), index.h("ion-col", { "size-sm": "6", size: "12" }, index.h("fireenjin-select", { ref: (el) => (this.stepsSelectEl = el), labelPosition: "stacked", "data-fill": true, multiple: true, name: "steps", label: "Steps", options: stepOptions, required: true })))))), index.h("ion-card", null, index.h("ion-item-divider", null, "Steps", index.h("ion-button", { slot: "end", onClick: () => this.showSteps() }, "Show Steps")), index.h("ion-grid", null, index.h("ion-row", null, this.toggleSteps && (index.h("ion-col", null, (this.steps || []).map((step) => (index.h("ion-item", { onClick: () => this.stepSelect(step) }, index.h("ion-label", null, (step === null || step === void 0 ? void 0 : step.name) || "name")))))))), index.h("fireenjin-form", { formData: this.step, ref: (el) => (this.stepFormEl = el), endpoint: !this.stepId ? "addStep" : "editStep", documentId: this.stepId, disableLoader: true, beforeSubmit: async (data) => ({
          ...data,
          ...this.stepInput,
        }) }, index.h("ion-item-divider", null, "Add Step"), index.h("ion-grid", null, index.h("ion-row", null, index.h("ion-col", { "size-sm": "6", size: "12" }, index.h("fireenjin-input", { name: "name", label: "Name", labelPosition: "stacked", value: (_g = this.step) === null || _g === void 0 ? void 0 : _g.name })), index.h("ion-col", { "size-sm": "4", size: "12" }, index.h("fireenjin-select-tags", { name: "tags", labelPosition: "stacked", label: "Tags", value: (_h = this.step) === null || _h === void 0 ? void 0 : _h.tags, allowAdding: true, options: [
          {
            label: "Important",
            value: "important",
          },
        ] })), index.h("ion-col", { "size-sm": "2", size: "12" }))), index.h("ion-item", { class: "json-editor-field", style: { zIndex: "3" } }, index.h("ion-label", null, index.h("h2", null, "Before Html"), index.h("fireenjin-code-editor", { ref: (el) => (this.beforeEl = el), autoExpand: true, language: "html", name: "beforeHtml", value: (_j = this.step) === null || _j === void 0 ? void 0 : _j.beforeHtml }))), index.h("ion-item", { class: "json-editor-field", style: { zIndex: "3" } }, index.h("ion-label", null, index.h("h2", null, "After Html"), index.h("fireenjin-code-editor", { ref: (el) => (this.afterEl = el), autoExpand: true, language: "html", name: "afterHtml", value: (_k = this.step) === null || _k === void 0 ? void 0 : _k.afterHtml })))), index.h("ion-item-divider", null, "Fields", index.h("ion-button", { slot: "end", onClick: () => this.showFields() }, "Show Fields")), this.toggleFields &&
        (((_l = this.step) === null || _l === void 0 ? void 0 : _l.fields) || []).map((field) => (index.h("ion-item", { onClick: () => this.fieldSelect(field) }, index.h("ion-label", null, field)))), index.h("fireenjin-form", { formData: this.step, name: "addFieldForm" }, index.h("ion-item", { class: "json-editor-field", style: { zIndex: "3" } }, index.h("ion-label", null, index.h("h2", null, "Add Fields"), index.h("fireenjin-code-editor", { ref: (el) => (this.fieldEl = el), autoExpand: true, language: "json", name: "field", value: this.field }))))))))),
      index.h("floodteam-navigation-footer", null),
    ];
  }
};
AppFlow.style = appFlowCss;

exports.app_flow = AppFlow;
