import { Component, h, Listen, Method, Prop, State, Watch } from "@stencil/core";
import { Token } from "authly";
import { MerchantKeyInfoUnpack } from "../model";
import * as verification from "./verification";
import { VerificationError } from "./VerificationError";
export class PayfuncCardInput {
  constructor() {
    this.state = "created";
  }
  async componentWillLoad() {
    this.merchant = await MerchantKeyInfoUnpack(this.apiKey);
    const styleLink = document.querySelector("link[rel=stylesheet][href^='https://theme.payfunc.com/']");
    if (styleLink) {
      const themeLink = styleLink.href.substring(26);
      this.theme = themeLink.substring(0, themeLink.indexOf("/"));
    }
  }
  verifyTimer() {
    let data;
    if (!this.verify) {
      window.clearTimeout(this.responseTimer);
      this.responseTimer = undefined;
    }
    else if (this.verify && this.verify.show === false && this.verify.data)
      this.responseTimer = window.setTimeout(() => {
        var _a, _b;
        if ((_b = (data = (_a = this.verify) === null || _a === void 0 ? void 0 : _a.data)) === null || _b === void 0 ? void 0 : _b.threeDSServerTransID) {
          console.log("Method call max server response time reached.");
          window.clearTimeout(this.responseTimer);
          this.responseTimer = undefined;
          this.frame.send("card", {
            name: "methodTimeout",
            value: {
              card: this.value,
              key: this.apiKey,
              parent: window.location.origin,
              verificationId: data.threeDSServerTransID,
              version: ["2.1.0", "2.2.0"].includes(data.messageVersion) ? data.messageVersion : undefined,
            },
          });
        }
      }, 15000);
  }
  async handleTrigger(event) {
    if (!VerificationError.is(event.detail.value)) {
      this.verify = undefined;
      if (Token.is(event.detail.value))
        this.value = event.detail.value;
      this.state = event.detail.name == "cardTokenSuccess" ? "succeeded" : "failed";
      if (this.received) {
        this.received(this.state, event.detail.value);
        this.received = undefined;
      }
    }
  }
  async submit(input, error) {
    if (Token.is(input))
      this.value = input;
    if (VerificationError.is(error) && this.merchant && this.value)
      this.verify = await verification.from(error, this.merchant, this.value);
    return new Promise(callback => {
      if (this.frame) {
        this.received = (_, response) => callback(response);
        const value = { card: this.value, key: this.apiKey, parent: window.location.origin };
        this.frame.send("card", !error ? { name: "submit", value } : { name: "cardCheck", value: Object.assign(Object.assign({}, value), { error }) });
        this.state = "processing";
      }
    });
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    const parameters = [];
    this.theme && parameters.push({ key: "theme", value: this.theme });
    this.cosmetic &&
      parameters.push({
        key: "cosmetic",
        value: encodeURIComponent(typeof this.cosmetic == "string" ? this.cosmetic : JSON.stringify(this.cosmetic)),
      });
    const parametersString = parameters.length > 0 ? "?" + parameters.map(param => `${param.key}=${param.value}`).join("&") : "";
    return [
      this.merchant ? (h("smoothly-frame", { url: ((_b = (_a = this.merchant) === null || _a === void 0 ? void 0 : _a.card) === null || _b === void 0 ? void 0 : _b.url) + "/ui/card-tokenizer/" + parametersString, origin: ((_d = (_c = this.merchant) === null || _c === void 0 ? void 0 : _c.card) === null || _d === void 0 ? void 0 : _d.url) ? new URL((_f = (_e = this.merchant) === null || _e === void 0 ? void 0 : _e.card) === null || _f === void 0 ? void 0 : _f.url).origin : undefined, name: "card", ref: (element) => (this.frame = element) })) : ([]),
      this.verify ? (this.verify.show ? (h("smoothly-dialog", { color: "default", closable: true },
        h("smoothly-frame", { url: this.verify.url, origin: ((_h = (_g = this.merchant) === null || _g === void 0 ? void 0 : _g.card) === null || _h === void 0 ? void 0 : _h.url) ? new URL((_k = (_j = this.merchant) === null || _j === void 0 ? void 0 : _j.card) === null || _k === void 0 ? void 0 : _k.url).origin : undefined, name: "parent", style: { height: "90vh" } }))) : (h("smoothly-frame", { hidden: true, url: this.verify.url, origin: ((_m = (_l = this.merchant) === null || _l === void 0 ? void 0 : _l.card) === null || _m === void 0 ? void 0 : _m.url) ? new URL((_p = (_o = this.merchant) === null || _o === void 0 ? void 0 : _o.card) === null || _p === void 0 ? void 0 : _p.url).origin : undefined, name: "parent", style: { height: "90vh" } }))) : ([]),
    ];
  }
  static get is() { return "payfunc-card-input"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "apiKey": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "api-key",
      "reflect": false
    },
    "state": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "\"failed\" | \"succeeded\" | \"processing\" | \"created\"",
        "resolved": "\"created\" | \"failed\" | \"processing\" | \"succeeded\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "state",
      "reflect": true,
      "defaultValue": "\"created\""
    },
    "value": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "Token",
        "resolved": "string | undefined",
        "references": {
          "Token": {
            "location": "import",
            "path": "authly"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "value",
      "reflect": false
    },
    "verify": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "{ show?: boolean; url: string; data: Record<string, string> }",
        "resolved": "undefined | { show?: boolean | undefined; url: string; data: Record<string, string>; }",
        "references": {
          "Record": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "cosmetic": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "| string\n\t\t| {\n\t\t\t\ttext?: { background?: string; color?: string }\n\t\t\t\tlineColor?: string\n\t\t\t\tfontFamily?: string\n\t\t\t\tdangerColor?: string\n\t\t  }",
        "resolved": "string | undefined | { text?: { background?: string | undefined; color?: string | undefined; } | undefined; lineColor?: string | undefined; fontFamily?: string | undefined; dangerColor?: string | undefined; }",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "cosmetic",
      "reflect": false
    }
  }; }
  static get states() { return {
    "theme": {},
    "merchant": {}
  }; }
  static get methods() { return {
    "submit": {
      "complexType": {
        "signature": "(input: Token | undefined, error?: Error | undefined) => Promise<Token | Error | undefined>",
        "parameters": [{
            "tags": [],
            "text": ""
          }, {
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "Error": {
            "location": "import",
            "path": "gracely"
          },
          "Token": {
            "location": "import",
            "path": "authly"
          }
        },
        "return": "Promise<string | Error | undefined>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    }
  }; }
  static get watchers() { return [{
      "propName": "verify",
      "methodName": "verifyTimer"
    }]; }
  static get listeners() { return [{
      "name": "trigger",
      "method": "handleTrigger",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
