import { Component, Element, Event, h, Prop, State } from "@stencil/core";
import * as gracely from "gracely";
import { Notice } from "smoothly";
import { Connection, Customer } from "@payfunc/model";
import * as translation from "./translation";
export class IntergiroCustomerActions {
  constructor() {
    this.selected = {};
  }
  componentWillLoad() {
    this.t = translation.create(this.element);
  }
  retry() {
    this.notice.emit(Notice.execute(this.t("Retrying payment."), async () => {
      const response = await Connection.put("retry", {});
      return gracely.Error.is(response)
        ? [false, this.t("Your payment was declined.")]
        : [true, this.t("Payment succeeded.")];
    }));
  }
  equalize() {
    const idArray = Object.keys(this.selected);
    this.notice.emit(Notice.execute(this.t("Equalizing balance..."), async () => {
      let result;
      const response = await Promise.all(idArray.map(id => Connection.delete(`customer/${id}/balance`)));
      const [succeeded, failed] = response.reduce(([s, f], e) => (gracely.Error.is(e) ? [s, ++f] : [++s, f]), [0, 0]);
      if (succeeded > 0)
        result = [
          true,
          idArray.length > 1
            ? this.t("$0 of $1 balances were equalized.", succeeded, idArray.length)
            : this.t("Balance was equalized."),
        ];
      else
        result = [
          false,
          idArray.length > 1
            ? this.t("Failed to equalize $0 of $1 balances.", failed, idArray.length)
            : this.t("Failed to equalize balance."),
        ];
      return result;
    }));
  }
  toggle(action) {
    this.opened = action == this.opened ? "" : action;
  }
  render() {
    const customers = Object.values(this.selected).filter(Customer.is);
    const retry = customers.every(c => c.status == "suspended" || c.status == "pending");
    return [
      h("div", { style: customers.length > 0 ? { right: "0" } : {} },
        h("smoothly-trigger", { color: "success", name: "cancel", onClick: () => this.toggle("order") },
          h("smoothly-icon", { toolTip: this.opened == "order" ? this.t("Cancel") : this.t("Create order"), name: this.opened == "order" ? "close" : "add" })),
        h("smoothly-trigger", { hidden: !this.whitelist, slot: "icon", color: "success", onClick: () => this.toggle("subscription") },
          h("smoothly-icon", { toolTip: this.t("Create subscription"), name: "calendar-outline" })),
        h("smoothly-trigger", { color: "warning", hidden: !this.whitelist, slot: "icon", onClick: () => this.equalize() },
          h("smoothly-icon", { toolTip: this.t("Equalize balance to zero"), name: "cash-outline" })),
        h("smoothly-trigger", { color: "danger", disabled: !retry, name: "retry", onClick: () => this.retry() },
          h("smoothly-icon", { toolTip: this.t("Retry payment"), name: "refresh" }))),
      (this.opened == "order" || this.opened == "subscription") && Object.entries(this.selected).length > 0
        ? [
          this.opened == "order" ? (h("portal-create-order", { type: "customer", selected: this.selected })) : (h("ig-subscription-create", { customers: this.selected })),
          h("div", { class: "arrow" }),
          h("div", { class: "background", onClick: () => this.toggle(this.opened) }),
        ]
        : "",
    ];
  }
  static get is() { return "ig-customer-actions"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "selected": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{ [id: string]: Customer | undefined }",
        "resolved": "{ [id: string]: Customer | undefined; }",
        "references": {
          "Customer": {
            "location": "import",
            "path": "@payfunc/model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "{}"
    },
    "whitelist": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "whitelist",
      "reflect": false
    }
  }; }
  static get states() { return {
    "t": {},
    "opened": {}
  }; }
  static get events() { return [{
      "method": "notice",
      "name": "notice",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "Notice",
        "resolved": "Notice",
        "references": {
          "Notice": {
            "location": "import",
            "path": "smoothly"
          }
        }
      }
    }]; }
  static get elementRef() { return "element"; }
}
