import { toastController } from "@ionic/core";
import { Build, h, } from "@stencil/core";
import { format } from "date-fns";
import * as Handlebars from "handlebars";
import injectScript from "../../../helpers/injectScript";
import state from "../../../store";
export class AppTotaller {
  constructor() {
    this.totallerId = undefined;
    this.totaller = {};
    this.testTotals = {};
    this.totallerResults = {};
    this.totalsToView = {};
    this.totalsColor = {};
    this.totalsDocs = [];
    this.graphLabels = [];
    this.graphType = "line";
    this.graphDatasets = [];
    this.currentTab = "setup";
  }
  async onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) === "addTotaller") {
      try {
        const routerEl = document.querySelector("ion-router");
        routerEl.push(`/totallers/${(_d = (_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.addTotaller) === null || _d === void 0 ? void 0 : _d.id}`);
      }
      catch (e) {
        console.log("error redirecting");
      }
    }
    else if (((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.endpoint) === "editTotaller") {
      (await toastController.create({
        message: "Totaller saved successfully!",
        duration: 2000,
      })).present();
    }
    else if (((_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.endpoint) === "calculateTotaller") {
      this.totallerResults =
        ((_j = (_h = (_g = event === null || event === void 0 ? void 0 : event.detail) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.calculateTotaller) === null || _j === void 0 ? void 0 : _j.results) || {};
    }
    else if (((_k = event === null || event === void 0 ? void 0 : event.detail) === null || _k === void 0 ? void 0 : _k.endpoint) === "findTotaller") {
      console.log(event);
      this.totaller = ((_m = (_l = event === null || event === void 0 ? void 0 : event.detail) === null || _l === void 0 ? void 0 : _l.data) === null || _m === void 0 ? void 0 : _m.totaller) || null;
      ((((_o = this.totaller) === null || _o === void 0 ? void 0 : _o.sums) && Object.keys((_p = this.totaller) === null || _p === void 0 ? void 0 : _p.sums)) || []).map((sumName) => {
        this.totalsToView[sumName] = true;
      });
      this.runTotaller();
    }
  }
  async onChange(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    if (["collection", "name", "sampleData"].includes(event.target.name)) {
      this.totaller[event.target.name] =
        ((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "sampleData" &&
          typeof ((_b = event === null || event === void 0 ? void 0 : event.target) === null || _b === void 0 ? void 0 : _b.value) === "string"
          ? JSON.parse(event.target.value)
          : ((_c = event === null || event === void 0 ? void 0 : event.target) === null || _c === void 0 ? void 0 : _c.value) || null;
    }
    else if (event.target.name.includes("color.")) {
      const fieldName = event.target.name.split(".")[1];
      this.totalsColor[fieldName] = event.target.value;
      this.setGraphData();
    }
    else if (event.target.name.includes(".logic")) {
      const fieldName = event.target.name.split(".")[1];
      if (!((_e = (_d = this.totaller) === null || _d === void 0 ? void 0 : _d.sums) === null || _e === void 0 ? void 0 : _e[fieldName]))
        this.totaller.sums[fieldName] = {};
      this.totaller.sums[fieldName].logic =
        typeof ((_f = event === null || event === void 0 ? void 0 : event.target) === null || _f === void 0 ? void 0 : _f.value) === "string"
          ? JSON.parse(event.target.value)
          : ((_g = event === null || event === void 0 ? void 0 : event.target) === null || _g === void 0 ? void 0 : _g.value) || {};
      this.setGraphData();
    }
    else if (event.target.name.includes("toggle.")) {
      const fieldName = event.target.name.split(".")[1];
      this.totalsToView[fieldName] = !!(event === null || event === void 0 ? void 0 : event.target.checked);
      this.setGraphData();
    }
    else if (event.target.name === "graphType") {
      this.graphType = event.target.value;
      this.setGraphData();
    }
    else if (event.target.name === "graphPath") {
      if (!((_j = (_h = event.target) === null || _h === void 0 ? void 0 : _h.value) === null || _j === void 0 ? void 0 : _j.length))
        return;
      const collectionPath = Handlebars.compile(event.target.value)({
        totaller: this.totaller,
        data: ((_k = this.totaller) === null || _k === void 0 ? void 0 : _k.sampleData) ? this.totaller.sampleData : {},
      });
      const pathParts = collectionPath.split("/");
      pathParts.pop();
      // const totalsQuery = await this.db.getCollection(pathParts.join("/"));
      const docs = [];
      const labels = [];
      const totalsDocs = [];
      for (const doc of docs) {
        labels.push(doc.id);
        totalsDocs.push({ ...doc.data(), id: doc.id });
      }
      this.totalsDocs = totalsDocs;
      this.graphLabels = labels;
      this.setGraphData();
    }
    else if (event.target.name === "type") {
      const value = event.target.value;
      if (value === "year") {
        this.pathInputEl.value = `/totals/{{totaller.id}}/year/{{#if data.createdAt}}{{date data.createdAt 'yyyy' }}{{else}}unknown{{/if}}`;
      }
      else if (value === "quarter") {
        this.pathInputEl.value = `/totals/{{totaller.id}}/quarter/{{#if data.createdAt}}{{date data.createdAt 'yyyy-Q' }}{{else}}unknown{{/if}}`;
      }
      else if (value === "month") {
        this.pathInputEl.value = `/totals/{{totaller.id}}/month/{{#if data.createdAt}}{{date data.createdAt 'yyyy-Q-MM' }}{{else}}unknown{{/if}}`;
      }
      else if (value === "week") {
        this.pathInputEl.value = `/totals/{{totaller.id}}/week/{{#if data.createdAt}}{{date data.createdAt 'yyyy-Q-MM-ww' }}{{else}}unknown{{/if}}`;
      }
      else if (value === "day") {
        this.pathInputEl.value = `/totals/{{totaller.id}}/day/{{#if data.createdAt}}{{date data.createdAt 'yyyy-Q-MM-ww-dd' }}{{else}}unknown{{/if}}`;
      }
    }
  }
  randomNumber() {
    return Math.floor(Math.random() * 100);
  }
  setGraphData() {
    var _a;
    const sumNames = Object.keys(this.totalsToView).filter((sumName) => !!this.totalsToView[sumName]);
    this.graphLabels =
      this.graphType === "pie"
        ? sumNames.map((sumName) => { var _a, _b, _c; return ((_c = (_b = (_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) === null || _b === void 0 ? void 0 : _b[sumName]) === null || _c === void 0 ? void 0 : _c.name) || sumName; })
        : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    this.graphDatasets =
      this.graphType === "pie"
        ? [
          {
            label: ((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.name) || "Pie Chart",
            data: sumNames.map(() => this.randomNumber()),
            backgroundColor: sumNames.map((sumName) => this.totalsColor[sumName]
              ? this.totalsColor[sumName]
              : this.randomColor()),
          },
        ]
        : sumNames.map((sumName) => {
          var _a, _b, _c;
          return ({
            label: ((_c = (_b = (_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) === null || _b === void 0 ? void 0 : _b[sumName]) === null || _c === void 0 ? void 0 : _c.name) || sumName,
            data: [
              this.randomNumber(),
              this.randomNumber(),
              this.randomNumber(),
              this.randomNumber(),
              this.randomNumber(),
              this.randomNumber(),
              this.randomNumber(),
            ],
            backgroundColor: this.totalsColor[sumName]
              ? this.totalsColor[sumName]
              : this.randomColor(),
            borderColor: this.totalsColor[sumName]
              ? this.totalsColor[sumName]
              : this.randomColor(),
          });
        });
  }
  randomColor() {
    return "#" + Math.floor(Math.random() * 16777215).toString(16);
  }
  removePath(event, removeIndex) {
    var _a;
    event.preventDefault();
    event.stopPropagation();
    if (!confirm("Are you sure you want to remove this path for totaller?"))
      return;
    const paths = ((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.paths) || {};
    delete paths[removeIndex];
    this.totaller = {
      ...this.totaller,
      paths,
    };
  }
  removeSum(event, sumName) {
    var _a;
    event.preventDefault();
    event.stopPropagation();
    if (!confirm("Are you sure you want to remove this sum for totaller?"))
      return;
    const sums = ((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) ? this.totaller.sums : {};
    delete sums[sumName];
    this.totaller = {
      ...this.totaller,
      sums,
    };
  }
  addPath(event) {
    var _a, _b;
    event.preventDefault();
    event.stopPropagation();
    const paths = ((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.paths) || {};
    paths[((_b = this.pathTypeInputEl) === null || _b === void 0 ? void 0 : _b.value) || new Date().toISOString()] = `${this.pathInputEl.value}`;
    this.totaller = {
      ...this.totaller,
      paths,
    };
    this.pathInputEl.value = null;
    this.pathTypeInputEl.value = null;
  }
  addSum(event) {
    event.preventDefault();
    event.stopPropagation();
    this.totaller = {
      ...this.totaller,
      sums: {
        ...(this.totaller.sums || {}),
        [this.sumInputEl.value]: {
          var: "data.amount",
        },
      },
    };
  }
  async fetchTotaller() {
    this.fireenjinFetch.emit({
      endpoint: "findTotaller",
      params: {
        id: this.totallerId,
      },
    });
  }
  testAdd() {
    this.runTotaller("add");
    this.testTotals = { ...this.testTotals };
  }
  testSubtract() {
    this.runTotaller("delete");
    this.testTotals = { ...this.testTotals };
  }
  testReset() {
    this.totaller = { ...this.totaller };
    this.testTotals = {};
    this.runTotaller();
  }
  runTotaller(action) {
    var _a;
    for (const path of Object.values(((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.paths) || {})) {
      this.runTotallerForPath(path, action);
    }
  }
  runTotallerForPath(path, action) {
    var _a, _b, _c, _d;
    const totals = this.testTotals[path] ? this.testTotals[path] : {};
    for (const sumName of Object.keys(((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) || {})) {
      const calculation = (_d = (_c = (_b = this.totaller) === null || _b === void 0 ? void 0 : _b.sums) === null || _c === void 0 ? void 0 : _c[sumName]) === null || _d === void 0 ? void 0 : _d.logic;
      // Delete or Edit
      if (["delete", "edit"].includes(action)) {
        const calculatedSum = window.jsonLogic.apply(calculation, {
          totaller: this.totaller,
          data: this.totaller.sampleData,
          totals,
        });
        totals[sumName] =
          parseFloat(totals[sumName] ? totals[sumName] : 0) -
            parseFloat(calculatedSum ? calculatedSum : 0);
      }
      // Add or Edit
      if (["add", "edit"].includes(action)) {
        const calculatedSum = window.jsonLogic.apply(calculation, {
          totaller: this.totaller,
          data: this.totaller.sampleData,
          totals,
        });
        totals[sumName] =
          totals && totals[sumName]
            ? parseFloat(totals[sumName] ? totals[sumName] : 0) +
              parseFloat(calculatedSum ? calculatedSum : 0)
            : parseFloat(calculatedSum ? calculatedSum : 0);
      }
      if (!action) {
        totals[sumName] = 0;
      }
    }
    this.testTotals[path] = totals;
    return this.testTotals[path];
  }
  async sync() {
    var _a, _b, _c, _d, _e, _f, _g;
    if (!((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.id) ||
      !confirm("Are you sure you want to sync this to the live site, it cannot be undone?"))
      return;
    let response;
    const data = {
      collection: ((_b = this.totaller) === null || _b === void 0 ? void 0 : _b.collection) || null,
      name: ((_c = this.totaller) === null || _c === void 0 ? void 0 : _c.name) || null,
      paths: ((_d = this.totaller) === null || _d === void 0 ? void 0 : _d.paths) || [],
      sampleData: ((_e = this.totaller) === null || _e === void 0 ? void 0 : _e.sampleData) || {},
      sums: ((_f = this.totaller) === null || _f === void 0 ? void 0 : _f.sums) || {},
    };
    try {
      response = await fetch(`https://us-central1-${((_g = state === null || state === void 0 ? void 0 : state.config) === null || _g === void 0 ? void 0 : _g.env) === "live" ? "ftms-ca85b" : "floodteam-app"}.cloudfunctions.net/api/totaller/${this.totaller.id}`, {
        method: "POST",
        body: JSON.stringify(data),
      });
    }
    catch (e) {
      console.log("Error syncing totaller to live site!");
    }
    return (response === null || response === void 0 ? void 0 : response.json) ? response.json() : null;
  }
  async rerunTotals() {
    this.totallerResults = {};
    if (!confirm("This will recalculate all totals and cannot be undone, are you sure?"))
      return;
    this.fireenjinSubmit.emit({
      endpoint: "calculateTotaller",
      data: {
        id: this.totallerId,
        save: true,
      },
    });
  }
  async viewResults() {
    this.totallerResults = {};
    this.fireenjinSubmit.emit({
      endpoint: "calculateTotaller",
      data: { id: this.totallerId },
    });
  }
  componentWillLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    injectScript("https://cdn.jsdelivr.net/npm/json-logic-js@2.0.1/logic.js");
  }
  async componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    Handlebars.registerHelper("formatUSD", (amount) => {
      const formatter = new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
        minimumFractionDigits: 2,
      });
      return formatter.format(amount ? amount : 0);
    });
    Handlebars.registerHelper("date", (str, pattern = "MM/dd/yyyy", options = {}) => {
      try {
        return format(new Date(Date.parse(str)), pattern, options);
      }
      catch (e) {
        return "";
      }
    });
    if ((Build === null || Build === void 0 ? void 0 : Build.isBrowser) && this.totallerId && this.totallerId !== "new") {
      this.fetchTotaller();
    }
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    return [
      h("ion-tab-bar", null, h("ion-tab-button", { onClick: () => (this.currentTab = "setup") }, h("ion-icon", { name: "hammer" }), h("ion-label", null, "Setup")), h("ion-tab-button", { onClick: () => (this.currentTab = "test") }, h("ion-icon", { name: "flask" }), h("ion-label", null, "Test")), h("ion-tab-button", { onClick: () => (this.currentTab = "run") }, h("ion-icon", { name: "caret-forward-circle" }), h("ion-label", null, "Run")), h("ion-tab-button", { onClick: () => (this.currentTab = "graph") }, h("ion-icon", { name: "bar-chart" }), h("ion-label", null, "Graph"))),
      h("ion-content", { class: "ion-padding" }, h("div", { style: { display: this.currentTab === "setup" ? "block" : "none" } }, h("fireenjin-form", { ref: (el) => (this.formEl = el), endpoint: this.totallerId === "new" ? "addTotaller" : "editTotaller", documentId: this.totallerId && this.totallerId === "new"
          ? null
          : this.totallerId, formData: {
          sums: ((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) || {},
          paths: this.totaller.paths || [],
        }, name: "totaller", disableEnterButton: true, hideControls: true }, h("ion-card", null, h("ion-card-content", null, h("fireenjin-input", { type: "text", name: "name", label: "Name", labelPosition: "stacked", value: ((_b = this.totaller) === null || _b === void 0 ? void 0 : _b.name) || "", required: true, silence: true }), h("fireenjin-input", { type: "text", name: "collection", label: "Source Collection", labelPosition: "stacked", value: ((_c = this.totaller) === null || _c === void 0 ? void 0 : _c.collection) || "", required: true, silence: true }))), h("ion-card", { class: "ion-no-padding" }, h("ion-item-divider", null, "List of Paths"), h("fireenjin-form", { onSubmit: (event) => this.addPath(event), hideControls: true, disableLoader: true }, h("ion-grid", { class: "ion-no-padding" }, h("ion-row", { class: "ion-align-items-end ion-no-padding" }, h("ion-col", { size: "3" }, h("floodteam-input-totaller-type", { ref: (el) => (this.pathTypeInputEl = el) })), h("ion-col", { size: "7" }, h("ion-item", { style: {
          width: "90%",
          margin: "0 auto",
          display: "block",
        } }, h("ion-input", { ref: (el) => (this.pathInputEl = el), placeholder: "/totals/{{totaller.id}}/newTotal", type: "text", required: true }))), h("ion-col", { size: "2", class: "ion-padding-horizontal" }, h("ion-button", { type: "submit", class: "ion-float-right" }, "Add"))), h("ion-row", { id: "paths" }, h("ion-col", { class: "ion-padding" }, Object.entries(((_d = this.totaller) === null || _d === void 0 ? void 0 : _d.paths) || {})
        .reverse()
        .map(([index, path]) => (h("ion-item", null, h("ion-badge", { slot: "start" }, index), h("ion-label", { "text-wrap": true }, path), h("ion-button", { fill: "clear", color: "danger", onClick: (event) => this.removePath(event, index) }, "Remove", h("ion-icon", { slot: "start", name: "trash" })))))))))), h("ion-card", { class: "ion-no-padding" }, h("ion-item-divider", null, "List of Sums"), h("fireenjin-form", { onSubmit: (event) => this.addSum(event), hideControls: true, disableLoader: true }, h("ion-grid", { class: "ion-no-padding" }, h("ion-row", { class: "ion-align-items-end ion-no-padding" }, h("ion-col", null, h("ion-item", { style: {
          width: "90%",
          margin: "0 auto",
          display: "block",
        } }, h("ion-input", { ref: (el) => (this.sumInputEl = el), placeholder: "Name of new Sum", type: "text", required: true }))), h("ion-col", { size: "2", class: "ion-padding-horizontal" }, h("ion-button", { type: "submit", class: "ion-float-right" }, "Add"))), h("ion-row", { id: "paths" }, h("ion-col", { class: "ion-padding" }, ((_e = this.totaller) === null || _e === void 0 ? void 0 : _e.sums)
        ? Object.keys(this.totaller.sums)
          .reverse()
          .map((sumName) => {
          var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
          return (h("ion-item", null, h("ion-grid", null, h("ion-row", null, h("ion-col", { style: { maxWidth: "60px" } }, h("ion-input", { style: {
              display: "block",
              margin: "0 auto",
              height: "100%",
              width: "40px",
            }, type: "color", name: `sums.${sumName}.color`, value: ((_c = (_b = (_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) === null || _b === void 0 ? void 0 : _b[sumName]) === null || _c === void 0 ? void 0 : _c.color) || null })), h("ion-col", null, h("fireenjin-input", { name: `sums.${sumName}.name`, labelPosition: "stacked", label: `Name (${sumName})`, value: ((_f = (_e = (_d = this.totaller) === null || _d === void 0 ? void 0 : _d.sums) === null || _e === void 0 ? void 0 : _e[sumName]) === null || _f === void 0 ? void 0 : _f.name) || sumName })), h("ion-col", null, h("fireenjin-input", { name: `sums.${sumName}.description`, labelPosition: "stacked", label: "Description", value: ((_j = (_h = (_g = this.totaller) === null || _g === void 0 ? void 0 : _g.sums) === null || _h === void 0 ? void 0 : _h[sumName]) === null || _j === void 0 ? void 0 : _j.description) || null })), h("ion-col", null, h("fireenjin-select", { name: `sums.${sumName}.format`, label: "Format", labelPosition: "stacked", options: [
              {
                label: "USD Dollar",
                value: "usd",
              },
              {
                label: "None",
                value: null,
              },
            ], value: ((_m = (_l = (_k = this.totaller) === null || _k === void 0 ? void 0 : _k.sums) === null || _l === void 0 ? void 0 : _l[sumName]) === null || _m === void 0 ? void 0 : _m.format) || null }))), h("ion-row", null, h("ion-col", null, h("fireenjin-code-editor", { language: "json", name: `sums.${sumName}.logic`, value: typeof ((_q = (_p = (_o = this.totaller) === null || _o === void 0 ? void 0 : _o.sums) === null || _p === void 0 ? void 0 : _p[sumName]) === null || _q === void 0 ? void 0 : _q.logic) === "object"
              ? JSON.stringify(this.totaller.sums[sumName]
                .logic, null, 4)
              : ((_t = (_s = (_r = this.totaller) === null || _r === void 0 ? void 0 : _r.sums) === null || _s === void 0 ? void 0 : _s[sumName]) === null || _t === void 0 ? void 0 : _t.logic) || "" })))), h("div", { slot: "end" }, h("ion-button", { expand: "full", fill: "clear", color: "dark", onClick: () => {
              var _a, _b, _c;
              const newSumName = prompt("What woud you like the new sum name to be? (EX: myNewSumName)", sumName);
              if (!newSumName)
                return;
              this.totaller.sums[newSumName] = {
                logic: ((_c = (_b = (_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) === null || _b === void 0 ? void 0 : _b[sumName]) === null || _c === void 0 ? void 0 : _c.logic) || null,
                id: newSumName,
              };
              delete this.totaller.sums[sumName];
              this.totaller = { ...this.totaller };
            } }, h("ion-icon", { slot: "start", name: "text" }), "Rename"), h("ion-button", { expand: "full", fill: "clear", color: "primary", onClick: () => {
              this.totaller.sums[`${sumName}Copy`] =
                this.totaller.sums[sumName];
              this.totaller = { ...this.totaller };
            } }, h("ion-icon", { slot: "start", name: "copy" }), "Duplicate"), h("ion-button", { expand: "full", fill: "clear", color: "danger", onClick: (event) => this.removeSum(event, sumName) }, "Remove", h("ion-icon", { slot: "start", name: "trash" })))));
        })
        : null))))))), h("div", { style: { display: this.currentTab === "test" ? "block" : "none" } }, h("ion-grid", null, h("ion-row", null, h("ion-col", { size: "12", sizeMd: "6" }, h("ion-card", { class: "ion-no-padding" }, h("ion-item-divider", null, "Test Data"), h("fireenjin-code-editor", { language: "json", name: "sampleData", value: JSON.stringify(((_f = this.totaller) === null || _f === void 0 ? void 0 : _f.sampleData) ? this.totaller.sampleData : {}) }), h("ion-item-divider", null, "Test Controls"), h("ion-grid", null, h("ion-row", null, h("ion-col", { size: "4" }, h("ion-button", { fill: "clear", expand: "block", onClick: () => this.testAdd() }, "Add ", h("ion-icon", { name: "add", slot: "end" }))), h("ion-col", { size: "4" }, h("ion-button", { fill: "clear", expand: "block", color: "danger", onClick: () => this.testSubtract() }, "Subtract ", h("ion-icon", { name: "remove", slot: "end" }))), h("ion-col", { size: "4" }, h("ion-button", { expand: "block", color: "medium", fill: "clear", onClick: () => this.testReset() }, "Reset ", h("ion-icon", { name: "refresh", slot: "end" }))))))), h("ion-col", { size: "12", sizeMd: "6" }, h("ion-card", { class: "ion-no-padding" }, h("ion-item-divider", null, "Results"), Object.values(((_g = this.totaller) === null || _g === void 0 ? void 0 : _g.paths) || {})
        .reverse()
        .map((path) => (h("ion-item", null, h("ion-label", null, h("ion-text", { "text-wrap": true }, path), h("fireenjin-json-viewer", { watcher: true, innerHTML: JSON.stringify(this.testTotals[path] ? this.testTotals[path] : {}) })))))))))), h("div", { style: { display: this.currentTab === "run" ? "block" : "none" } }, h("ion-grid", null, h("ion-row", null, h("ion-col", { size: "12", sizeMd: "5" }, h("ion-card", { class: "ion-no-padding" }, h("ion-item-divider", { color: "dark" }, "Controls"), h("ion-button", { expand: "block", fill: "clear", onClick: () => this.viewResults() }, "View Results on Collection"), h("ion-button", { expand: "block", fill: "clear", color: "warning", onClick: () => this.sync() }, "Sync to Live Site"), h("ion-button", { expand: "block", fill: "clear", color: "danger", onClick: () => this.rerunTotals() }, "Rerun Totaller on Collection"))), h("ion-col", { size: "12", sizeMd: "7" }, h("ion-card", { class: "ion-no-padding" }, h("ion-item-divider", { class: "ion-padding-end", color: "dark" }, "Results", this.totallerResults &&
        Object.keys(this.totallerResults) && (h("ion-badge", { slot: "end" }, Object.keys(this.totallerResults).length))), this.totallerResults &&
        Object.keys(this.totallerResults).map((path) => (h("ion-item", null, h("ion-label", { class: "ion-text-wrap" }, h("h2", null, path), h("fireenjin-json-viewer", { openDepth: 0, innerHTML: JSON.stringify(this.totallerResults[path]
            ? this.totallerResults[path]
            : {}) })))))))))), h("div", { style: { display: this.currentTab === "graph" ? "block" : "none" } }, h("ion-card", { class: "ion-no-padding" }, h("ion-grid", null, h("ion-row", null, h("ion-col", { size: "5" }, h("ion-item-divider", null, "Graph Data"), h("fireenjin-select", { label: "Graph", name: "graphType", value: this.graphType, options: [
          {
            label: "line",
            value: "line",
          },
          {
            label: "bar",
            value: "bar",
          },
          {
            label: "pie",
            value: "pie",
          },
        ] }), h("fireenjin-select", { name: "graphPath", label: "Totals By", interface: "action-sheet", interfaceOptions: {}, options: Object.keys(((_h = this.totaller) === null || _h === void 0 ? void 0 : _h.paths) || {}).map((value) => ({
          label: value,
          value,
        })) }), h("ion-item-divider", null, "Totals to View"), (((_j = this.totaller) === null || _j === void 0 ? void 0 : _j.sums)
        ? Object.keys(this.totaller.sums)
        : []).map((sumName) => {
        var _a, _b, _c;
        if (!this.totalsColor[sumName])
          this.totalsColor[sumName] =
            ((_c = (_b = (_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) === null || _b === void 0 ? void 0 : _b[sumName]) === null || _c === void 0 ? void 0 : _c.color) ||
              this.randomColor();
        return (h("ion-item", null, h("ion-toggle", { name: `toggle.${sumName}`, checked: true }), h("ion-label", { class: "ion-text-capitalize" }, sumName.replace(/([A-Z]+)*([A-Z][a-z])/g, "$1 $2")), h("input", { type: "color", name: `color.${sumName}`, slot: "end", value: this.totalsColor[sumName], onChange: (e) => this.onChange(e) })));
      })), h("ion-col", { size: "7" }, console.log(this.graphLabels, this.graphDatasets), h("fireenjin-graph", { type: this.graphType, labels: this.graphLabels, datasets: this.graphDatasets }))))))),
      h("floodteam-navigation-footer", null, h("floodteam-title-bar", { back: "/totallers", disableUnderline: true }, h("ion-breadcrumbs", null, h("ion-breadcrumb", { href: "/totallers" }, h("ion-icon", { class: "ft-icon-style", slot: "start", name: "calculator" }), "Totallers"), h("ion-breadcrumb", { href: "#", onClick: () => {
          var _a;
          return this.fireenjinTrigger.emit({
            name: "pin",
            payload: {
              icon: "calculator",
              href: `/totallers/${this.totallerId}`,
              name: ((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.name) || "Totaller",
            },
          });
        } }, h("ion-icon", { color: ((_k = ((state === null || state === void 0 ? void 0 : state.pins) || [])
          .map((pin) => pin === null || pin === void 0 ? void 0 : pin.href)) === null || _k === void 0 ? void 0 : _k.includes(`/totallers/${this.totallerId}`))
          ? "primary"
          : null, slot: "start", name: "pin" }), ((_l = this.totaller) === null || _l === void 0 ? void 0 : _l.name) || "???")), h("ion-button", { slot: "end", fill: "solid", color: "primary", onClick: () => { var _a, _b; return (_b = (_a = this.formEl) === null || _a === void 0 ? void 0 : _a.submit) === null || _b === void 0 ? void 0 : _b.call(_a); } }, "Save"))),
    ];
  }
  static get is() { return "app-totaller"; }
  static get originalStyleUrls() {
    return {
      "$": ["app-totaller.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["app-totaller.css"]
    };
  }
  static get properties() {
    return {
      "totallerId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "totaller-id",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "totaller": {},
      "testTotals": {},
      "totallerResults": {},
      "totalsToView": {},
      "totalsColor": {},
      "totalsDocs": {},
      "graphLabels": {},
      "graphType": {},
      "graphDatasets": {},
      "currentTab": {}
    };
  }
  static get events() {
    return [{
        "method": "fireenjinFetch",
        "name": "fireenjinFetch",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "FireEnjinFetchEvent",
          "resolved": "FireEnjinFetchEvent",
          "references": {
            "FireEnjinFetchEvent": {
              "location": "import",
              "path": "@fireenjin/sdk"
            }
          }
        }
      }, {
        "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": "fireenjinSuccess",
        "method": "onSuccess",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "ionChange",
        "method": "onChange",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinCodeChange",
        "method": "onChange",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
