import { h, Host } from "@stencil/core";
import iFrameResize from "iframe-resizer/js/iframeResizer";
import { FrameCommunicationService } from "../../utils/frame-comunication-service";
import { FormControlErrorText } from "./form-helpers/form-control-error-text";
import packageJson from "../../../package.json";
import { iframeInputStyles } from "./iframe-input-styles-state";
import { MessageEventType } from "../../components/checkout/message-event-types";
import { input, inputFocused, inputInvalid, inputInvalidAndFocused, label } from "../../styles/parts";
export class IframeInput {
    constructor() {
        this.isFocused = false;
        this.isValid = true;
        this.dispatchMessageEvent = (event) => {
            const { eventType, data } = event.data;
            if ((data === null || data === void 0 ? void 0 : data.id) !== this.inputId) {
                return;
            }
            if (eventType === 'focused') {
                this.isFocused = true;
            }
            if (eventType === 'blurred') {
                this.isFocused = false;
            }
        };
    }
    disconnectedCallback() {
        this.frameService.removeMessageListener(this.dispatchMessageEvent);
    }
    async validate() {
        const response = await this.frameService
            .postMessageWithResponseListener(MessageEventType.validate);
        this.isValid = response.isValid;
        this.errorText = response.error.message;
        return response;
    }
    async tokenize(clientId, paymentMethodMetadata, account) {
        return this.frameService.postMessageWithResponseListener(MessageEventType.tokenize, {
            clientId,
            paymentMethodMetadata,
            account,
            componentVersion: packageJson.version,
        });
    }
    initializeFrameCommunicationService() {
        var _a;
        this.frameService = new FrameCommunicationService(this.iframeElement, this.iframeOrigin);
        (_a = this.frameService) === null || _a === void 0 ? void 0 : _a.addMessageListener(this.dispatchMessageEvent);
    }
    get part() {
        if (this.isFocused && !this.isValid) {
            return inputInvalidAndFocused;
        }
        if (!this.isValid) {
            return inputInvalid;
        }
        if (this.isFocused) {
            return inputFocused;
        }
        return input;
    }
    get style() {
        if (this.isFocused) {
            if (!this.isValid) {
                return iframeInputStyles.focusedAndInvalid;
            }
            return iframeInputStyles.focused;
        }
        return null;
    }
    get urlParams() {
        // map the iframeInputStyles.fontStyles properties to the urlParams 
        // and encode each property with btoa
        const encodedObject = Object.fromEntries(Object
            .entries(iframeInputStyles.fontStyles)
            .map(([key, value]) => [key, btoa(String(value))]));
        const params = new URLSearchParams(encodedObject).toString();
        return params;
    }
    render() {
        return (h(Host, { key: '60e76f1a33ddd4ea5b89cd31a1b6906ff53c5ddb', class: "form-group d-flex flex-column" }, h("div", { key: '5fdef33ae8deb616929478d06fddc01b97233f0a', style: {
                visibility: this.iframeLoaded ? 'visible' : 'hidden',
                height: this.iframeLoaded ? 'auto' : '0',
            } }, h("label", { key: 'e37adecf5024d4c77561d3ca269f49c398fc8fd7', class: "form-label", htmlFor: "", part: label }, this.label || ''), h("div", { key: '206a703cd84d713155aa754576410f495b4329fe', class: `p-0 d-flex form-control ${this.isValid ? '' : 'is-invalid'}`, part: this.part, style: Object.assign(Object.assign({}, this.style), { overflow: 'hidden' }) }, h("iframe", { key: '214ecd5b4fa9d075b91ea73b9edd09fdfa0cdf12', id: this.inputId, name: this.inputId, src: `${this.iframeOrigin}?${this.urlParams}`, ref: el => {
                this.iframeElement = el;
                this.initializeFrameCommunicationService();
            }, width: "100%", onLoad: () => {
                iFrameResize({
                    log: false,
                    onResized: () => {
                        this.iframeLoaded.emit();
                    }
                }, this.iframeElement);
            } })), h(FormControlErrorText, { key: 'bec41e86a063eacb8f1f741b446c64db540d9e4d', errorText: this.errorText, name: this.inputId }))));
    }
    static get is() { return "iframe-input"; }
    static get properties() {
        return {
            "inputId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "input-id"
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "label"
            },
            "iframeOrigin": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "iframe-origin"
            }
        };
    }
    static get states() {
        return {
            "isFocused": {},
            "isValid": {},
            "errorText": {}
        };
    }
    static get events() {
        return [{
                "method": "iframeLoaded",
                "name": "iframeLoaded",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "validate": {
                "complexType": {
                    "signature": "() => Promise<any>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<any>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "tokenize": {
                "complexType": {
                    "signature": "(clientId: string, paymentMethodMetadata: IPaymentMethodMetadata, account?: string) => Promise<any>",
                    "parameters": [{
                            "name": "clientId",
                            "type": "string",
                            "docs": ""
                        }, {
                            "name": "paymentMethodMetadata",
                            "type": "ISavedPaymentMethod & ISubmitCheckoutArgs",
                            "docs": ""
                        }, {
                            "name": "account",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "IPaymentMethodMetadata": {
                            "location": "import",
                            "path": "../../api/PaymentMethod",
                            "id": "src/api/PaymentMethod.ts::IPaymentMethodMetadata"
                        }
                    },
                    "return": "Promise<any>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
}
