import { Build, Component, Event, h, Listen, Prop, State, } from "@stencil/core";
import * as jsonLogic from "json-logic-js";
import { toastController } from "@ionic/core";
import renderHandlebars from "../../../helpers/renderHandlebars";
import testJob from "../../../helpers/seeds/testJob";
import testLocation from "../../../helpers/seeds/testLocation";
import testUser from "../../../helpers/seeds/testUser";
export class appTrigger {
  constructor() {
    this.seedData = {
      addJob: testJob,
      editJob: testJob,
      addLocation: testLocation,
      editLocation: testLocation,
      addUser: testUser,
      editUser: testUser,
    };
    this.trigger = {};
    this.triggerWillFire = false;
    this.currentTab = "settings";
  }
  ionChange(event) {
    var _a, _b, _c, _d, _e;
    this.trigger[event.target.name] = event.target.value;
    if (((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "type" && ((_b = this.seedData) === null || _b === void 0 ? void 0 : _b[(_c = this.trigger) === null || _c === void 0 ? void 0 : _c.type])) {
      this.trigger.sampleData = (_d = this.seedData) === null || _d === void 0 ? void 0 : _d[(_e = this.trigger) === null || _e === void 0 ? void 0 : _e.type];
    }
    this.trigger = { ...this.trigger };
  }
  onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) === "findTrigger") {
      this.trigger = ((_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.trigger) || null;
    }
    else if (((_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.endpoint) === "addTemplate" &&
      this.triggerId === "new") {
      const routerEl = document.querySelector("ion-router");
      this.triggerId = ((_g = (_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.addTemplate) === null || _g === void 0 ? void 0 : _g.id) || "new";
      if (routerEl)
        routerEl.push(`/triggers/${this.triggerId}`);
    }
  }
  async onChange(event) {
    console.log(event.target.name);
    if (event.target.name === "payload") {
      this.trigger.payload = JSON.parse(event.target.value);
      this.generateSampleOutput();
    }
    else if (event.target.name === "sampleData") {
      this.trigger.sampleData = JSON.parse(event.target.value);
      this.generateSampleOutput();
      this.triggerWillFire = this.checkIfTriggerFires(this.trigger.when);
    }
    else if (event.target.name === "when") {
      this.trigger.when = event.target.value;
      this.triggerWillFire = this.checkIfTriggerFires(this.trigger.when);
    }
  }
  checkIfTriggerFires(when) {
    return !!jsonLogic.apply(typeof when === "string" ? JSON.parse(when) : when, {
      data: this.trigger.sampleData,
    });
  }
  generateSampleOutput() {
    var _a, _b, _c;
    let output = renderHandlebars(JSON.stringify(((_a = this.trigger) === null || _a === void 0 ? void 0 : _a.payload) || {}), {
      data: ((_b = this.trigger) === null || _b === void 0 ? void 0 : _b.sampleData) || {},
    });
    output = output.replace('"@data"', JSON.stringify(((_c = this.trigger) === null || _c === void 0 ? void 0 : _c.sampleData) || {}));
    this.jsonViewerEl.innerHTML = output;
    return output;
  }
  async save() {
    this.formEl.submit();
    (await toastController.create({
      message: "Trigger saved successfully!",
      duration: 2000,
    })).present();
  }
  async componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    this.fireenjinTrigger.emit({
      name: "subscribe",
      payload: {
        collection: "triggers",
        id: this.triggerId,
        callback: () => {
          this.formEl.fetchData();
        },
      },
    });
  }
  disconnectedCallback() {
    this.fireenjinTrigger.emit({
      name: "unsubscribe",
      payload: {
        collection: "triggers",
        id: this.triggerId,
      },
    });
  }
  render() {
    var _a, _b, _c, _d;
    return [
      h("ion-content", { class: "ion-padding" },
        h("floodteam-title-bar", { back: "/triggers" },
          "Edit Trigger",
          h("ion-buttons", { slot: "end" },
            h("ion-button", { color: this.triggerWillFire ? "warning" : "medium", fill: this.triggerWillFire ? "solid" : "outline", disabled: !this.triggerWillFire, onClick: () => this.fireenjinSubmit.emit({
                endpoint: "addAlert",
                data: JSON.parse(this.generateSampleOutput()),
              }) }, "Fire Trigger"),
            h("ion-button", { fill: "solid", color: "primary", onClick: () => this.save() }, "Save"))),
        h("ion-segment", { onIonChange: (event) => { var _a; return (this.currentTab = ((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value) || "settings"); }, color: "secondary", scrollable: true, value: this.currentTab },
          h("ion-segment-button", { value: "settings", layout: "icon-start" },
            h("ion-label", null, "Settings"),
            h("ion-icon", { name: "settings" })),
          h("ion-segment-button", { value: "action", layout: "icon-start" },
            h("ion-label", null, "Action"),
            h("ion-icon", { name: "flash" })),
          h("ion-segment-button", { value: "test", layout: "icon-start" },
            h("ion-label", null, "Test"),
            h("ion-icon", { name: "flashlight" }))),
        h("fireenjin-form", { ref: (el) => (this.formEl = el), fetch: this.triggerId === "new" ? null : "findTrigger", "fetch-key": "trigger", endpoint: this.triggerId === "new" ? "addTrigger" : "editTrigger", documentId: this.triggerId === "new" ? null : this.triggerId, beforeSubmit: async () => {
            return {
              ...this.trigger,
              action: "alert",
              active: this.trigger.active === "on",
            };
          }, filterData: "name,type,when,action,payload,sampleData,active", hideControls: true },
          h("ion-card", { style: {
              display: this.currentTab === "settings" ? "block" : "none",
            } },
            h("ion-card-content", null,
              h("ion-grid", null,
                h("ion-row", null,
                  h("ion-col", { size: "10" },
                    h("fireenjin-input", { "data-fill": true, labelPosition: "stacked", type: "text", name: "name", label: "Name", required: true })),
                  h("ion-col", { size: "2" },
                    h("fireenjin-toggle", { value: (_a = this.trigger) === null || _a === void 0 ? void 0 : _a.active, color: "secondary", lines: "none", label: "Active", labelPosition: "stacked", name: "active" })))),
              h("fireenjin-select", { labelPosition: "stacked", "data-fill": true, name: "type", label: "Type", options: [
                  {
                    label: "On Job Add",
                    value: "addJob",
                  },
                  {
                    label: "On Job Edit",
                    value: "editJob",
                  },
                  {
                    label: "On User Add",
                    value: "addUser",
                  },
                  {
                    label: "On User Edit",
                    value: "editUser",
                  },
                  {
                    label: "On Location Add",
                    value: "addLocation",
                  },
                  {
                    label: "On Location Edit",
                    value: "editLocation",
                  },
                  {
                    label: "On Log Add",
                    value: "addLog",
                  },
                  {
                    label: "On Note Add",
                    value: "addNote",
                  },
                  {
                    label: "On Note Edit",
                    value: "editNote",
                  },
                  {
                    label: "On Payable Add",
                    value: "addPayable",
                  },
                  {
                    label: "On Payable Edit",
                    value: "editPayable",
                  },
                  {
                    label: "On Payment Add",
                    value: "addPayment",
                  },
                  {
                    label: "On Payment Edit",
                    value: "editPayment",
                  },
                ], required: true }),
              h("ion-item", null,
                h("ion-label", null,
                  h("h2", null, "When is this triggered?"),
                  (Build === null || Build === void 0 ? void 0 : Build.isBrowser) && (h("fireenjin-code-editor", { value: ((_b = this.trigger) === null || _b === void 0 ? void 0 : _b.when) || "{}", language: "json", name: "when" })))))),
          h("ion-card", { style: {
              display: this.currentTab === "action" ? "block" : "none",
            } },
            h("ion-card-content", null,
              h("fireenjin-input", { labelPosition: "stacked", "data-fill": true, type: "text", name: "action", label: "Action", value: "alert", disabled: true, required: true }),
              h("ion-item", null,
                h("ion-label", null,
                  h("h2", null, "What payload is passed to the action?"),
                  (Build === null || Build === void 0 ? void 0 : Build.isBrowser) && (h("fireenjin-code-editor", { value: JSON.stringify(((_c = this.trigger) === null || _c === void 0 ? void 0 : _c.payload) || {
                      types: ["email"],
                      emails: [],
                      userIds: [],
                      payload: {},
                      options: {},
                      sendAt: null,
                      templateId: null,
                      tags: [],
                    }, null, 4), language: "json", name: "payload" })))))),
          h("ion-card", { style: {
              display: this.currentTab === "test" ? "block" : "none",
            } },
            h("ion-card-content", null,
              h("ion-grid", null,
                h("ion-row", null,
                  h("ion-col", { size: "12", sizeMd: "6" }, (Build === null || Build === void 0 ? void 0 : Build.isBrowser) && (h("fireenjin-code-editor", { value: JSON.stringify(((_d = this.trigger) === null || _d === void 0 ? void 0 : _d.sampleData) || {}, null, 4), language: "json", name: "sampleData" }))),
                  h("ion-col", { size: "12", sizeMd: "6" },
                    h("fireenjin-json-viewer", { ref: (el) => (this.jsonViewerEl = el), watcher: true })))))))),
    ];
  }
  static get is() { return "app-trigger"; }
  static get originalStyleUrls() { return {
    "$": ["app-trigger.css"]
  }; }
  static get styleUrls() { return {
    "$": ["app-trigger.css"]
  }; }
  static get properties() { return {
    "triggerId": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "trigger-id",
      "reflect": false
    }
  }; }
  static get states() { return {
    "trigger": {},
    "triggerWillFire": {},
    "currentTab": {}
  }; }
  static get events() { return [{
      "method": "fireenjinFetch",
      "name": "fireenjinFetch",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "fireenjinSubmit",
      "name": "fireenjinSubmit",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "FireEnjinSubmitEvent",
        "resolved": "FireEnjinSubmitEvent",
        "references": {
          "FireEnjinSubmitEvent": {
            "location": "import",
            "path": "@fireenjin/sdk"
          }
        }
      }
    }, {
      "method": "fireenjinTrigger",
      "name": "fireenjinTrigger",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "FireEnjinTriggerInput",
        "resolved": "FireEnjinTriggerInput",
        "references": {
          "FireEnjinTriggerInput": {
            "location": "import",
            "path": "@fireenjin/sdk"
          }
        }
      }
    }]; }
  static get listeners() { return [{
      "name": "ionChange",
      "method": "ionChange",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinSuccess",
      "method": "onSuccess",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinCodeChange",
      "method": "onChange",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "ionRouteDidChange",
      "method": "componentDidLoad",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
//# sourceMappingURL=app-trigger.js.map