import { Component, Element, Event, h, Listen, Method, Prop, State } from "@stencil/core";
import { get as getFlag } from "flagly";
import { Error } from "gracely";
import { Token } from "authly";
import { Trigger } from "smoothly";
import "../../installment-details";
import "../../invoice-details";
import "../../card-details";
import { isVerificationError, paymentHasVerify, paymentIs, } from "../../model";
import { paymentDetailsCreate } from "./PaymentDetails";
import * as translation from "./translation";
export class IntergiroPaymentOptions {
  async componentWillLoad() {
    this.t = translation.create(this.element);
  }
  handleToggle(event) {
    console.log(event);
    this.selected = event.detail.name;
  }
  findDeferOrderId(partialOrder) {
    return "payment" in partialOrder && partialOrder.payment.type == "defer" ? partialOrder.id : undefined;
  }
  async submit(partialOrder, apiKey, merchant) {
    if (this.selected && this.details) {
      const detail = this.details.find(d => d.type == this.selected);
      if (detail && detail.element && detail.element.getPayment) {
        let payment = await detail.element.getPayment(partialOrder, apiKey);
        if (!payment) {
          this.paymentFailed.emit({ property: "noPayment", description: "noMessage" });
          console.log("3D authorization aborted.");
        }
        else {
          const submitOrder = Object.assign(Object.assign({}, partialOrder), { payment });
          let order = await this.submitHelper(this.findDeferOrderId(partialOrder), submitOrder);
          ({ order, payment } = await this.confirmPayment(order, partialOrder, payment, apiKey, merchant, detail));
          return await this.resolveOrder(order);
        }
      }
    }
  }
  async confirmPayment(order, partialOrder, payment, apiKey, merchant, detail) {
    var _a, _b;
    if (isVerificationError(order) && Error.is(order)) {
      if (payment && ((_a = detail.element) === null || _a === void 0 ? void 0 : _a.confirmPayment)) {
        payment = await ((_b = detail.element) === null || _b === void 0 ? void 0 : _b.confirmPayment(partialOrder, payment, apiKey, order));
        if (payment) {
          const submitOrder = Object.assign(Object.assign({}, partialOrder), { payment });
          order = await this.submitHelper(this.findDeferOrderId(partialOrder), submitOrder);
          if (isVerificationError(order))
            ({ order, payment } = await this.confirmPayment(order, partialOrder, payment, apiKey, merchant, detail));
        }
        else {
          this.paymentFailed.emit({ property: "noPayment", description: "noMessage" });
          console.log("3D authorization aborted.");
        }
      }
      else {
        this.paymentFailed.emit({ property: "noPayment", description: "noMessage" });
        console.log("3D authorization aborted.");
      }
    }
    return { order, payment };
  }
  resolveOrder(order) {
    return new Promise(resolve => {
      if (Error.is(order)) {
        this.paymentFailed.emit(order);
        console.log("Error creating payment.");
      }
      else if (Token.is(order))
        resolve(order);
      else if (order && paymentHasVerify(order.payment) && order.payment.verify.url) {
        this.url = order.payment.verify.url;
        this.resolve = resolve;
      }
      else {
        this.paymentFailed.emit({ property: "noPayment", description: this.t("Error creating payment.") });
        console.log("Error creating payment.");
      }
    });
  }
  async submitHelper(id, order) {
    let result;
    const t = this.t;
    if (!order.items || !order.currency) {
      this.paymentFailed.emit({
        property: "noPayment",
        description: t("Error: Order must contain items and currency."),
      });
      console.log("Error: must have items, currency");
    }
    else
      result = id ? await this.client.order.setPayment(order.payment, id) : await this.client.order.create(order, true);
    return result;
  }
  TriggerListener(event) {
    if (Trigger.is(event.detail) && (event.detail.name == "order" || event.detail.name == "fail") && this.resolve) {
      this.url = undefined;
      this.resolve(event.detail.value);
      event.preventDefault();
      event.stopPropagation();
    }
    else if (typeof event.detail == "object" && event.detail.name == "close" && this.verify) {
      console.log("payment-options close", event.detail);
      const order = this.verify[0];
      if (paymentIs(event.detail.value))
        order.payment = event.detail.value;
      this.verify[1](order);
      this.verify = undefined;
    }
    else if (Trigger.is(event.detail) && event.detail.name == "cardTokenFailed")
      this.paymentFailed.emit(event.detail.value);
  }
  render() {
    var _a;
    const t = this.t;
    if (this.options) {
      this.details = this.options
        .map(option => paymentDetailsCreate(option, this.cosmetic))
        .filter((detail) => !!detail);
      if (!this.selected && this.details && this.details.length > 0)
        this.selected = this.details[0].type;
    }
    return [
      this.url ? (h("smoothly-dialog", { color: "primary", closable: true },
        h("smoothly-frame", { url: this.url, name: "parent", style: { height: "60em" } }))) : (""),
      h("h3", null, getFlag((_a = this.flags) !== null && _a !== void 0 ? _a : {}, "transfer") ? t("Transfer") : t("Payment")),
      this.details && this.details.length > 0 ? (this.details.map(detail => (h("ig-payment-option", { id: detail.type, type: detail.type, selected: this.selected == detail.type, name: detail.name, brand: detail.brand }, detail.component)))) : (h("p", null, t("No payment options available."))),
    ];
  }
  static get is() { return "ig-payment-options"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "client": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "CheckoutClient",
        "resolved": "{ contact: Contact; order: Order; }",
        "references": {
          "CheckoutClient": {
            "location": "import",
            "path": "../../model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "cosmetic": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "cosmetic",
      "reflect": false
    },
    "options": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "PaymentOption[]",
        "resolved": "PaymentOption[]",
        "references": {
          "PaymentOption": {
            "location": "import",
            "path": "../../model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "selected": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "selected",
      "reflect": false
    },
    "flags": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Flags",
        "resolved": "undefined | { [flag: string]: boolean | Flags | undefined; }",
        "references": {
          "Flags": {
            "location": "import",
            "path": "flagly"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "t": {},
    "verify": {},
    "url": {}
  }; }
  static get events() { return [{
      "method": "paymentFailed",
      "name": "paymentFailed",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "trigger",
      "name": "trigger",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "Trigger",
        "resolved": "Trigger",
        "references": {
          "Trigger": {
            "location": "import",
            "path": "smoothly"
          }
        }
      }
    }]; }
  static get methods() { return {
    "submit": {
      "complexType": {
        "signature": "(partialOrder: Order | Omit<Order.Creatable, \"payment\">, apiKey: string, merchant: Payload) => Promise<SubmitResult>",
        "parameters": [{
            "tags": [],
            "text": ""
          }, {
            "tags": [],
            "text": ""
          }, {
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "SubmitResult": {
            "location": "import",
            "path": "./PaymentDetails"
          },
          "Order": {
            "location": "import",
            "path": "../../model"
          },
          "Omit": {
            "location": "global"
          },
          "Payload": {
            "location": "import",
            "path": "authly"
          },
          "PaymentCreatable": {
            "location": "import",
            "path": "../../model"
          }
        },
        "return": "Promise<SubmitResult>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    }
  }; }
  static get elementRef() { return "element"; }
  static get listeners() { return [{
      "name": "paymentOptionSelected",
      "method": "handleToggle",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "trigger",
      "method": "TriggerListener",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
