import { Component, Element, Event, h, Listen, Prop, State, Watch } from "@stencil/core";
import { get as getFlag } from "flagly";
import * as langly from "langly";
import { Identifier } from "authly";
import "smoothly";
import { Notice } from "smoothly";
import { ErrorMessage, isVerificationError } from "../model";
import * as translation from "./translation";
export class IntergiroCheckoutPayment {
  constructor() {
    this.processing = false;
    this.buttonDisabled = false;
  }
  async componentWillLoad() {
    var _a;
    this.t = translation.create(this.element);
    this.errorMessage = ErrorMessage.create("payment", (_a = langly.getLanguage(this.element)) !== null && _a !== void 0 ? _a : "en");
  }
  async handleSubmit(event) {
    event.preventDefault();
    let result = false;
    const t = this.t;
    if (this.paymentOptionsElement && this.merchant) {
      this.processing = true;
      if (!this.order.number)
        this.order.number = Identifier.generate(12);
      const order = await this.paymentOptionsElement.submit(this.order, this.apiKey, this.merchant);
      result = !!order;
      if (!result) {
        this.notice.emit(Notice.failed(t("Order could not be created.")));
        this.processing = false;
      }
      else
        this.signedOrder = order;
    }
    console.log("handleSubmit result", result);
    return result;
  }
  onUpdatedNotice(startProcessing) {
    if (this.responseTimer) {
      window.clearTimeout(this.responseTimer);
      this.responseTimer = undefined;
    }
    if (startProcessing) {
      this.responseTimer = window.setTimeout(() => {
        if (this.processing) {
          console.log("Max server response time reached.");
          this.notice.emit(Notice.failed(this.t("No response from payment server within time limit, please try again later.")));
          this.processing = false;
        }
        if (this.responseTimer) {
          window.clearTimeout(this.responseTimer);
          this.responseTimer = undefined;
        }
      }, 180000);
    }
  }
  async onPaymentFailed(event) {
    var _a, _b;
    if ((((_a = event.detail.content) === null || _a === void 0 ? void 0 : _a.property) == "pares" && ((_b = event.detail.content) === null || _b === void 0 ? void 0 : _b.url)) || isVerificationError(event.detail)) {
      if (this.responseTimer) {
        window.clearTimeout(this.responseTimer);
        this.responseTimer = undefined;
      }
    }
    else {
      this.processing = false;
      const message = this.errorMessage.generate(event);
      if (message && message != "noMessage")
        this.notice.emit(Notice.failed(message));
    }
  }
  componentDidRender() {
    if (this.signedOrder && this.submitElement)
      this.submitElement.submit();
  }
  render() {
    var _a, _b;
    const t = this.t;
    return [
      h("ig-payment-options", { client: this.client, options: this.options, cosmetic: this.cosmetic, flags: this.flags, ref: e => (this.paymentOptionsElement = e) }),
      h("ig-items-display", { items: !this.order.items ? [] : this.order.items, currency: this.order.currency, style: { border: "1x black" } }),
      h("smoothly-submit", { color: "success", prevent: true, expand: "block", processing: this.processing, onSubmit: (event) => this.handleSubmit(event), ref: (element) => (this.submitElement = element) }, this.processing ? t("Verifying") : getFlag((_a = this.flags) !== null && _a !== void 0 ? _a : {}, "transfer") ? t("Send") : t("Buy")),
      h("merchant-terms", { merchant: this.merchant, buttonName: getFlag((_b = this.flags) !== null && _b !== void 0 ? _b : {}, "transfer") ? t("Send") : t("Buy") }),
      h("card-logotypes", null),
      this.signedOrder ? h("input", { type: "hidden", name: "order", value: this.signedOrder }) : [],
    ];
  }
  static get is() { return "ig-checkout-payment"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "processing": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "processing",
      "reflect": true,
      "defaultValue": "false"
    },
    "order": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Order | Omit<Order, \"payment\">",
        "resolved": "Order | { number?: string | undefined; created: string; id: string; client?: string | undefined; customer?: string | Contact | undefined; items: number | Item | Item[]; currency: Currency; subscription?: string | undefined; event?: Event[] | undefined; status?: Status[] | StatusList | undefined; theme?: string | undefined; meta?: any; callback?: string | undefined; language?: Language | undefined; category?: \"purchase\" | \"withdrawal\" | undefined; }",
        "references": {
          "Order": {
            "location": "import",
            "path": "../model"
          },
          "Omit": {
            "location": "global"
          }
        }
      },
      "required": true,
      "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[] | undefined",
        "references": {
          "PaymentOption": {
            "location": "import",
            "path": "../model"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiKey": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "api-key",
      "reflect": false
    },
    "merchant": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MerchantKey",
        "resolved": "Key",
        "references": {
          "MerchantKey": {
            "location": "import",
            "path": "../model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "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": ""
      }
    },
    "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": ""
      }
    }
  }; }
  static get states() { return {
    "t": {},
    "signedOrder": {},
    "buttonDisabled": {},
    "errorMessage": {}
  }; }
  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"; }
  static get watchers() { return [{
      "propName": "processing",
      "methodName": "onUpdatedNotice"
    }]; }
  static get listeners() { return [{
      "name": "paymentFailed",
      "method": "onPaymentFailed",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
