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";
import state from "../../../store";
import getEventTypeOptions from "../../../helpers/getEventTypeOptions";
export class appTrigger {
  constructor() {
    this.seedData = {
      addJob: testJob,
      editJob: testJob,
      addLocation: testLocation,
      editLocation: testLocation,
      addUser: testUser,
      editUser: testUser,
      addLog: {
        id: "test-log",
      },
      addNote: {
        id: "test-note",
      },
      editNote: {
        id: "test-note",
      },
      addPayable: {
        id: "addPayable-test",
      },
      editPayable: {
        id: "payable-test",
      },
      addPayment: {
        id: "payment-test",
      },
      editPayment: {
        id: "payment-test",
      },
    };
    this.payloadKey = {
      addJob: "job",
      editJob: "job",
      addLocation: "location",
      editLocation: "location",
      addUser: "user",
      editUser: "user",
      addLog: "log",
      addNote: "note",
      editNote: "note",
      addPayable: "payable",
      editPayable: "payable",
      addPayment: "payment",
      editPayment: "payment",
    };
    this.sampleOutput = {};
    this.defaultAlertPayload = {
      types: ["email"],
      emails: [],
      userIds: [],
      payload: {},
      options: {},
      sendAt: null,
      templateId: null,
      tags: [],
    };
    this.defaultTotallerPayload = {
      totallerId: null,
      before: null,
      after: null,
      extras: {},
      mergeData: {},
      dryRun: false,
    };
    this.trigger = {};
    this.triggerWillFire = false;
    this.currentTab = "settings";
  }
  ionChange(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
    if (event &&
      event.target &&
      event.target.name &&
      !event.target.name.startsWith("ion-"))
      this.setByPath(this.trigger, event.target.name, event.target.value);
    console.log(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 = event.target) === null || _c === void 0 ? void 0 : _c.value])) {
      this.trigger.sampleData = (_d = this.seedData) === null || _d === void 0 ? void 0 : _d[(_e = event.target) === null || _e === void 0 ? void 0 : _e.value];
      const alertPayload = {
        types: ["email"],
        emails: [...(((_g = (_f = this.trigger) === null || _f === void 0 ? void 0 : _f.payload) === null || _g === void 0 ? void 0 : _g.emails) || [])],
        userIds: [...(((_j = (_h = this.trigger) === null || _h === void 0 ? void 0 : _h.payload) === null || _j === void 0 ? void 0 : _j.userIds) || [])],
        payload: {
          [this.payloadKey[(_k = this.trigger) === null || _k === void 0 ? void 0 : _k.type]]: "@data",
        },
        options: {},
        sendAt: null,
        templateId: ((_m = (_l = this.trigger) === null || _l === void 0 ? void 0 : _l.payload) === null || _m === void 0 ? void 0 : _m.templateId) || null,
        tags: [],
      };
      this.trigger.payload =
        ((_o = this.trigger) === null || _o === void 0 ? void 0 : _o.type) === "time"
          ? {
            action: "alert",
            queries: [
              {
                collection: "jobs",
                aliasAs: "job",
                filter: {
                  whereIn: {
                    status: [
                      "book",
                      "evaluate",
                      "claim",
                      "mitigate",
                      "monitor",
                      "review",
                    ],
                  },
                },
              },
            ],
            payload: alertPayload,
          }
          : alertPayload;
    }
    else if (((_p = event === null || event === void 0 ? void 0 : event.target) === null || _p === void 0 ? void 0 : _p.name) === "active") {
      this.trigger.active = (_q = event === null || event === void 0 ? void 0 : event.target) === null || _q === void 0 ? void 0 : _q.checked;
    }
    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);
    }
  }
  setByPath(obj, path, value) {
    const pList = path.split(".");
    const len = pList.length;
    for (let i = 0; i < len - 1; i++) {
      const elem = pList[i];
      if (!obj[elem])
        obj[elem] = {};
      obj = obj[elem];
    }
    obj[pList[len - 1]] = value;
  }
  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;
    this.sampleOutput = JSON.parse(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, _e, _f, _g, _h;
    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",
            };
          }, 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: getEventTypeOptions(), 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("ion-grid", null,
                h("ion-row", null,
                  h("ion-col", { size: "12", sizeMd: "7" },
                    h("fireenjin-select", { "data-fill": true, name: "action", label: "Action", labelPosition: "stacked", placeholder: "Select an Action", options: [
                        {
                          label: "Send Alert",
                          value: "alert",
                        },
                        {
                          label: "Run Totaller",
                          value: "totaller",
                        },
                      ], interface: "action-sheet" }),
                    h("fireenjin-select", { "data-fill": true, name: "payload.templateId", label: "Template", labelPosition: "stacked", placeholder: "Select Message Template", options: ((state === null || state === void 0 ? void 0 : state.templates) || [])
                        .filter((template) => !(template === null || template === void 0 ? void 0 : template.partial) && (template === null || template === void 0 ? void 0 : template.type) === "email")
                        .map((template) => ({
                        label: template === null || template === void 0 ? void 0 : template.subject,
                        value: template === null || template === void 0 ? void 0 : template.id,
                      })), interface: "action-sheet" }),
                    h("fireenjin-select-tags", { "data-fill": true, name: "payload.emails", label: "Email Addresses", options: (((_d = (_c = this.trigger) === null || _c === void 0 ? void 0 : _c.payload) === null || _d === void 0 ? void 0 : _d.emails) || []).map((email) => ({
                        label: email,
                        value: email,
                      })), allowAdding: true })),
                  h("ion-col", { size: "12", sizeMd: "5" },
                    h("floodteam-template", { id: "email-preview", allowFullscreen: true, zoom: 0.5, rawHtml: ((_e = ((state === null || state === void 0 ? void 0 : state.templates) || []).find((template) => { var _a, _b; return (template === null || template === void 0 ? void 0 : template.id) === ((_b = (_a = this.trigger) === null || _a === void 0 ? void 0 : _a.payload) === null || _b === void 0 ? void 0 : _b.templateId); })) === null || _e === void 0 ? void 0 : _e.html) || "", data: this.sampleOutput.payload || {} })))),
              h("ion-accordion-group", null,
                h("ion-accordion", null,
                  h("ion-item", { slot: "header" },
                    h("ion-label", null, "Advanced")),
                  h("ion-grid", { slot: "content" },
                    h("ion-row", null,
                      h("ion-col", null,
                        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(((_f = this.trigger) === null || _f === void 0 ? void 0 : _f.payload) ||
                                (((_g = this.trigger) === null || _g === void 0 ? void 0 : _g.action) === "totaller"
                                  ? this.defaultTotallerPayload
                                  : this.defaultAlertPayload), 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(((_h = this.trigger) === null || _h === void 0 ? void 0 : _h.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 })))))))),
      h("floodteam-navigation-footer", null),
    ];
  }
  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