import { Component, Element, Event, h, Listen, Prop, State } from "@stencil/core";
import { Error } from "gracely";
import { Notice } from "smoothly";
import { Key, Merchant as ModelMerchant } from "@payfunc/model";
import { IntergiroMonitor } from "../../../../index";
import * as translation from "./translation";
export class IntergiroMerchantRules {
  constructor() {
    this.state = "view";
    this.master = false;
  }
  async componentWillLoad() {
    var _a;
    this.t = translation.create(this.element);
    const user = (_a = IntergiroMonitor.client) === null || _a === void 0 ? void 0 : _a.me.user;
    if (user && ModelMerchant.is(user.merchant)) {
      const key = await Key.unpack(user.merchant.key.private, "agent");
      this.master = Key.is(key) && key.sub == "master";
    }
  }
  handleCanceled() {
    this.state = "view";
  }
  async updateMerchant(rule, message) {
    this.notice.emit(Notice.execute(this.t(message.execute), async () => {
      var _a;
      let result;
      const response = await ((_a = IntergiroMonitor.client) === null || _a === void 0 ? void 0 : _a.merchant.connection.patch(`merchant/${this.merchant.id}/rule`, rule));
      if (response && !Error.is(response)) {
        result = [true, this.t(message.success)];
        this.state = "view";
        this.merchantUpdated.emit();
        this.merchant = Object.assign({}, this.merchant);
      }
      else
        result = [false, this.t(message.fail)];
      return result;
    }));
  }
  async handleDeleted(event) {
    var _a;
    const rules = Object.assign({}, this.merchant.rules);
    rules[event.detail.key] = (_a = rules[event.detail.key]) === null || _a === void 0 ? void 0 : _a.filter(v => v != event.detail.value);
    this.merchant.rules[event.detail.key] = rules[event.detail.key];
    this.updateMerchant({ [event.detail.key]: rules[event.detail.key] }, { execute: "Deleting rule...", success: "Successfully deleted rule.", fail: "Failed to delete rule." });
    event === null || event === void 0 ? void 0 : event.stopPropagation();
  }
  async handleEdit(event) {
    var _a;
    const rules = Object.assign({}, this.merchant.rules);
    rules[event.detail.key] = (_a = rules[event.detail.key]) === null || _a === void 0 ? void 0 : _a.map(v => v == event.detail.oldValue ? (v = event.detail.newValue) : v);
    this.updateMerchant({ [event.detail.key]: rules[event.detail.key] }, { execute: "Editing rule...", success: "Successfully edited rule.", fail: "Failed to edit rule." });
    event === null || event === void 0 ? void 0 : event.stopPropagation();
  }
  handleAdd(event) {
    var _a;
    const key = event === null || event === void 0 ? void 0 : event.detail.key;
    const value = event === null || event === void 0 ? void 0 : event.detail.value;
    this.merchant.rules[key] ? (_a = this.merchant.rules[key]) === null || _a === void 0 ? void 0 : _a.push(value) : (this.merchant.rules[key] = [value]);
    this.updateMerchant({ [key]: this.merchant.rules[key] }, { execute: "Adding rule...", success: "Successfully added rule.", fail: "Failed to add rule." });
    event === null || event === void 0 ? void 0 : event.stopPropagation();
  }
  render() {
    const values = ["merchant", "agent", "other", ...Object.keys(this.merchant.rules)].reduce((r, v) => (r.includes(v) ? r : [...r, v]), []);
    if (!this.master)
      values.splice(values.indexOf("master"), 1);
    if (this.audience == "private")
      values.splice(values.indexOf("agent"), 1);
    const rules = Object.entries(this.merchant.rules);
    return [
      h("ig-merchant-rule-input", { add: true, values: values }),
      rules.map((r, index) => {
        var _a;
        return (r[1] && [
          h("section", null,
            h("label", { color: "light" },
              this.t("rules") +
                (r[1].length > 0
                  ? this.t(" by ") +
                    this.t(r[0] == "master" ? this.t("acquirer") : r[0]) +
                    " (" +
                    this.merchant.currency +
                    ")"
                  : ""),
              index == 0 && (h("smoothly-icon", { name: "add", toolTip: this.t("Add rule"), size: "medium", fill: "clear", color: "dark", onClick: () => (this.state = "add") }))), (_a = r[1]) === null || _a === void 0 ? void 0 :
            _a.map((rule, index) => [
              h("ig-merchant-rule", { style: index == 0 ? { "margin-top": "0.5em" } : {}, editable: this.master || index != 0, type: r[0], value: rule }),
            ])),
        ]);
      }),
    ];
  }
  static get is() { return "ig-merchant-rules"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "merchant": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "Merchant",
        "resolved": "Merchant",
        "references": {
          "Merchant": {
            "location": "import",
            "path": "@payfunc/model-acquirer"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "state": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "\"view\" | \"add\"",
        "resolved": "\"add\" | \"view\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "state",
      "reflect": true,
      "defaultValue": "\"view\""
    },
    "audience": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "\"private\" | \"agent\"",
        "resolved": "\"agent\" | \"private\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "audience",
      "reflect": true
    }
  }; }
  static get states() { return {
    "t": {},
    "master": {}
  }; }
  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"
          }
        }
      }
    }, {
      "method": "merchantUpdated",
      "name": "merchantUpdated",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get elementRef() { return "element"; }
  static get listeners() { return [{
      "name": "cancel",
      "method": "handleCanceled",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "delete",
      "method": "handleDeleted",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "edit",
      "method": "handleEdit",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "updated",
      "method": "handleAdd",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
