import { Build, h, } from "@stencil/core";
import renderHandlebars from "../../../helpers/renderHandlebars";
export class TotalGraph {
  constructor() {
    this.sumKeyToIndex = {};
    this.groupToDateFormat = {
      week: "yyyy-Q-MM-ww",
    };
    this.totallerId = undefined;
    this.type = "line";
    this.totaller = undefined;
    this.labels = [];
    this.dataSets = [];
    this.groupBy = "month";
    this.options = [];
    this.paths = {};
    this.totals = {};
    this.sumKeys = [];
  }
  ongroupByChanged() {
    this.populateGraph(this.totaller);
  }
  async onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
    if (event.detail.endpoint === "findTotaller") {
      this.totaller = ((_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.totaller) || null;
      this.populateGraph(this.totaller);
    }
    else if (((_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.endpoint) === "listTotals") {
      console.log(event.detail);
      this.filterTotals(((_e = (_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.totals) || []);
      const totallerId = (_j = (_h = (_g = (_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.event) === null || _g === void 0 ? void 0 : _g.detail) === null || _h === void 0 ? void 0 : _h.params) === null || _j === void 0 ? void 0 : _j.totallerId;
      this.totals = {
        ...this.totals,
        [totallerId]: (_l = (_k = event === null || event === void 0 ? void 0 : event.detail) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.totals,
      };
    }
  }
  filterTotals(allTotals) {
    // formatDate(new Date());
    const labels = [];
    let i = 0;
    for (const totals of (allTotals || []).reverse()) {
      if (this.groupBy === "week" && this.groupToDateFormat["week"] && i > 12)
        continue;
      i = i + 1;
      labels.push(totals === null || totals === void 0 ? void 0 : totals.id);
      this.sumKeys.map((sumKey) => {
        this.dataSets[this.sumKeyToIndex[sumKey]].data.push(totals[sumKey] || 0);
      });
      this.labels = labels;
    }
  }
  populateGraph(totaller) {
    var _a, _b;
    this.sumKeys = Object.keys(((_a = this.totaller) === null || _a === void 0 ? void 0 : _a.sums) || {});
    this.dataSets = Object.values(((_b = this.totaller) === null || _b === void 0 ? void 0 : _b.sums) || {}).map((sum, index) => {
      this.sumKeyToIndex[sum === null || sum === void 0 ? void 0 : sum.id] = index;
      return {
        label: (sum === null || sum === void 0 ? void 0 : sum.name) || (sum === null || sum === void 0 ? void 0 : sum.id),
        data: [],
        borderColor: (sum === null || sum === void 0 ? void 0 : sum.color) || this.randomColor(),
        backgroundColor: (sum === null || sum === void 0 ? void 0 : sum.color) || this.randomColor(),
      };
    });
    const totallerId = totaller === null || totaller === void 0 ? void 0 : totaller.id;
    for (const [key, path] of Object.entries((totaller === null || totaller === void 0 ? void 0 : totaller.paths) || {})) {
      if (!this.paths[totallerId])
        this.paths[totallerId] = {};
      this.paths[totallerId][key] = path;
      if (this.groupBy === key)
        this.fetchTotals(totallerId, path);
      if (!this.options.includes(key))
        this.options.push(key);
    }
    this.options = [...this.options];
    this.paths = { ...this.paths };
  }
  randomNumber() {
    return Math.random() * 10;
  }
  randomColor() {
    return "#" + Math.floor(Math.random() * 16777215).toString(16);
  }
  renderPathTemplate(totallerId, pathStr, timestamp) {
    return renderHandlebars(pathStr, {
      totaller: {
        id: totallerId,
      },
      data: {
        // THIS NEEDS TO BE CHANGED
        createdAt: timestamp || new Date(),
      },
    });
  }
  async fetchTotaller() {
    this.fireenjinFetch.emit({
      endpoint: "findTotaller",
      params: {
        id: this.totallerId,
      },
    });
  }
  async fetchTotals(totallerId, totalsPath, timestamp) {
    let path = this.renderPathTemplate(totallerId, totalsPath, timestamp);
    const pathParts = path.split("/");
    pathParts.pop();
    path = pathParts.join("/");
    this.fireenjinFetch.emit({
      endpoint: "listTotals",
      params: {
        totallerId,
        path,
      },
    });
  }
  async componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    this.fetchTotaller();
  }
  render() {
    return (h("fireenjin-graph", { type: this.type, labels: this.labels, datasets: this.dataSets, options: {
        plugins: {
          legend: {
            display: true,
            labels: {
              color: "rgb(255, 99, 132)",
            },
          },
        },
      } }));
  }
  static get is() { return "floodteam-total-graph"; }
  static get originalStyleUrls() {
    return {
      "$": ["total-graph.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["total-graph.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
      },
      "type": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"bar\" | \"line\" | \"pie\"",
          "resolved": "\"bar\" | \"line\" | \"pie\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "type",
        "reflect": false,
        "defaultValue": "\"line\""
      },
      "totaller": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "Totaller",
          "resolved": "{ __typename?: \"Totaller\"; collection?: string; createdAt?: string; createdBy?: User; id?: string; lastRunAt?: string; name?: string; paths?: any; sampleData?: any; sums?: any; updatedAt?: string; updatedBy?: User; }",
          "references": {
            "Totaller": {
              "location": "import",
              "path": "../../../sdk"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "labels": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "string[]",
          "resolved": "string[]",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "dataSets": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "any[]",
          "resolved": "any[]",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "groupBy": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "group-by",
        "reflect": false,
        "defaultValue": "\"month\""
      }
    };
  }
  static get states() {
    return {
      "options": {},
      "paths": {},
      "totals": {},
      "sumKeys": {}
    };
  }
  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"
            }
          }
        }
      }];
  }
  static get watchers() {
    return [{
        "propName": "groupBy",
        "methodName": "ongroupByChanged"
      }];
  }
  static get listeners() {
    return [{
        "name": "fireenjinSuccess",
        "method": "onSuccess",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
