import { Component, Event, h, Listen, Method, Prop, State } from "@stencil/core";
import { Base64, Token, Verifier } from "authly";
import { Card } from "@payfunc/model-card";
import { MerchantKeyInfoUnpack } from "../model";
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("/"));
    }
  }
  async handleTrigger(event) {
    var _a, _b, _c, _d, _e, _f;
    if (event.detail.value &&
      event.detail.value.status == 400 &&
      event.detail.value.type == "missing property" &&
      event.detail.value.content &&
      event.detail.value.content.property == "pares") {
      this.verify = {
        show: true,
        data: { pareq: event.detail.value.content.pareq },
        url: event.detail.value.content.url,
        issuer: (_c = (_b = (_a = this.merchant) === null || _a === void 0 ? void 0 : _a.card) === null || _b === void 0 ? void 0 : _b.url) !== null && _c !== void 0 ? _c : "",
      };
    }
    else if (event.detail.value &&
      event.detail.value.status == 400 &&
      event.detail.value.type == "malformed content" &&
      event.detail.value.content &&
      event.detail.value.content.description == "verification required" &&
      event.detail.value.content.details &&
      event.detail.value.content.details.url) {
      this.verify = {
        show: event.detail.value.content.details.visible,
        data: event.detail.value.content.details.data,
        url: event.detail.value.content.details.url,
        issuer: (_f = (_e = (_d = this.merchant) === null || _d === void 0 ? void 0 : _d.card) === null || _e === void 0 ? void 0 : _e.url) !== null && _f !== void 0 ? _f : "",
      };
    }
    else if (event.detail.name == "card") {
      this.verify = undefined;
      if (Token.is(event.detail.value)) {
        this.value = event.detail.value;
        await this.updateCard();
      }
      this.frame.send("card", {
        name: "cardCheck",
        value: { card: this.value, key: this.apiKey, parent: window.location.origin },
      });
    }
    else {
      this.verify = undefined;
      if (Token.is(event.detail.value)) {
        this.changed.emit((this.value = event.detail.value));
        await this.updateCard();
      }
      this.state = event.detail.name == "cardTokenSuccess" ? (this.state = "succeeded") : (this.state = "failed");
      if (this.received) {
        this.received(this.state, event.detail.value);
        this.received = undefined;
      }
    }
  }
  async updateCard() {
    var _a, _b, _c, _d, _e;
    if (this.value) {
      const verified = (_e = (_d = (_c = (_b = (await ((_a = Verifier.create()) === null || _a === void 0 ? void 0 : _a.verify(this.value)))) === null || _b === void 0 ? void 0 : _b.card) !== null && _c !== void 0 ? _c : (await Card.Token.verify(this.value))) !== null && _d !== void 0 ? _d : this.value) !== null && _e !== void 0 ? _e : "error";
      if (typeof verified == "string" || Card.Token.is(verified))
        this.cardId = verified;
    }
  }
  submit(input, error) {
    if (Token.is(input))
      this.value = input;
    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";
      }
    });
  }
  getIframeUrl(data) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
    const callback = Card.Token.is(this.cardId) && ((_a = this.verify) === null || _a === void 0 ? void 0 : _a.issuer)
      ? Card.Token.getVerificationTarget(this.cardId, (_b = this.verify) === null || _b === void 0 ? void 0 : _b.issuer, encodeURIComponent(window.location.origin))
      : `${(_c = this.verify) === null || _c === void 0 ? void 0 : _c.issuer}/card/${this.cardId}/verification?mode=iframe&merchant=${(_h = (_f = (_e = (_d = this.merchant) === null || _d === void 0 ? void 0 : _d.card) === null || _e === void 0 ? void 0 : _e.id) !== null && _f !== void 0 ? _f : (_g = this.merchant) === null || _g === void 0 ? void 0 : _g.sub) !== null && _h !== void 0 ? _h : "error"}&parent=${encodeURIComponent(window.location.origin)}`;
    console.log("Callback is ", callback);
    data = (_l = (_k = (_j = this.ch3d1Data(data, callback)) !== null && _j !== void 0 ? _j : this.ch3d2MethodData(data, callback)) !== null && _k !== void 0 ? _k : this.ch3d2ChallengeData(data, callback)) !== null && _l !== void 0 ? _l : data;
    const result = typeof data == "object" && Object.entries(data).length > 0
      ? Object.entries(data).reduce((a, b) => a + "&" + encodeURIComponent(b[0]) + "=" + encodeURIComponent(b[1]), "")
      : "";
    return "https://api.payfunc.com/redirect/post?target=" + encodeURIComponent((_o = (_m = this.verify) === null || _m === void 0 ? void 0 : _m.url) !== null && _o !== void 0 ? _o : "") + result;
  }
  ch3d1Data(data, callback) {
    var _a;
    let result = undefined;
    if (data.PaReq || data.pareq) {
      result = Object.assign({}, data);
      if (result.pareq) {
        result.PaReq = result.pareq;
        delete result.pareq;
      }
      if (!result.TermUrl)
        result.TermUrl = callback;
      if (!result.MD)
        result.MD = (_a = this.value) !== null && _a !== void 0 ? _a : "error";
    }
    return result;
  }
  ch3d2MethodData(data, callback) {
    let result = undefined;
    if (data.type == "method" && data.threeDSServerTransID) {
      result = {
        threeDSMethodData: Base64.encode(JSON.stringify({
          threeDSServerTransID: data.threeDSServerTransID,
          threeDSMethodNotificationURL: callback,
        }), "url", "="),
      };
    }
    return result;
  }
  ch3d2ChallengeData(data, callback) {
    let result = undefined;
    if (data.type == "challenge" && data.threeDSServerTransID) {
      result = {
        creq: Base64.encode(JSON.stringify({
          threeDSServerTransID: data.threeDSServerTransID,
          acsTransID: data.acsTransID,
          messageVersion: data.messageVersion,
          messageType: data.messageType,
          challengeWindowSize: data.challengeWindowSize,
        }), "url", "="),
      };
    }
    return result;
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    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/" + (this.theme ? "?theme=" + this.theme : ""), 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.getIframeUrl(this.verify.data), 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.getIframeUrl(this.verify.data), 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
    }
  }; }
  static get states() { return {
    "theme": {},
    "verify": {},
    "merchant": {}
  }; }
  static get events() { return [{
      "method": "changed",
      "name": "changed",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "Token",
        "resolved": "string",
        "references": {
          "Token": {
            "location": "import",
            "path": "authly"
          }
        }
      }
    }]; }
  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 listeners() { return [{
      "name": "trigger",
      "method": "handleTrigger",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
