import { Host, h } from "@stencil/core";
import { FormController } from "../../../ui-components/form/form";
import { Owner } from "../../../api/Identity";
import { identitySchemaByCountry } from "../schemas/business-identity-schema";
import { Button } from "../../../ui-components";
import { heading3 } from "../../../styles/parts";
import { BusinessFormClickActions } from "../utils/event-types";
import { makeGetIdentity, makePatchIdentity, makePostIdentity } from "../payment-provisioning/payment-provisioning-actions";
import { IdentityService } from "../../../api/services/business.service";
export class OwnerForm {
    loadingWatcher() {
        this.formLoading.emit(this.isLoading);
    }
    constructor() {
        this.isLoading = false;
        this.errors = {};
        this.owner = {};
        this.getData = () => {
            if (!this.getOwner) {
                return;
            }
            this.isLoading = true;
            this.getOwner({
                onSuccess: (response) => {
                    this.instantiateOwner(response.data);
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity,
                    });
                },
                final: () => (this.isLoading = false),
            });
        };
        this.sendData = () => {
            this.isLoading = true;
            return new Promise((resolve) => {
                if (this.ownerId) {
                    this.patchOwner({
                        payload: this.payload,
                        onSuccess: (response) => {
                            this.ownerSubmitted.emit({ id: response.data.id });
                            this.instantiateOwner(response.data);
                            resolve(true);
                        },
                        onError: ({ error, code, severity }) => {
                            this.errorEvent.emit({
                                message: error,
                                errorCode: code,
                                severity: severity,
                            });
                            resolve(false);
                        },
                        final: () => (this.isLoading = false),
                    });
                }
                else {
                    this.postOwner({
                        payload: this.payload,
                        onSuccess: (response) => {
                            this.ownerSubmitted.emit({ id: response.data.id });
                            this.instantiateOwner(response.data);
                            resolve(true);
                        },
                        onError: ({ error, code, severity }) => {
                            this.errorEvent.emit({
                                message: error,
                                errorCode: code,
                                severity: severity,
                            });
                            resolve(false);
                        },
                        final: () => (this.isLoading = false),
                    });
                }
            });
        };
        this.instantiateOwner = async (data) => {
            this.owner = Object.assign({}, new Owner(data));
            await this.formController.setInitialValues(this.owner);
        };
        this.handleAddOwner = () => {
            const eventName = this.ownerId ? BusinessFormClickActions.updateOwner : BusinessFormClickActions.addOwner;
            this.clickEvent.emit({ name: eventName });
        };
        this.handleRemoveOwner = () => {
            this.removeOwner(this.ownerId);
            this.clickEvent.emit({ name: BusinessFormClickActions.removeOwner });
        };
        this.validate = this.validate.bind(this);
        this.submit = this.submit.bind(this);
        this.validateAndSubmit = this.validateAndSubmit.bind(this);
    }
    async returnOwnerData() {
        return this.ownerId;
    }
    async getOwnershipPercentage() {
        var _a;
        return ((_a = this.formController.values.getValue()) === null || _a === void 0 ? void 0 : _a.ownership_percentage) || null;
    }
    async setOwnershipPercentageError(message) {
        this.formController.setFieldError('ownership_percentage', message);
    }
    async validate() {
        return this.formController.validate();
    }
    async submit() {
        const isValid = await this.validate();
        if (isValid) {
            return this.sendData();
        }
    }
    async validateAndSubmit(event) {
        event.preventDefault();
        const isValid = await this.validate();
        if (isValid) {
            this.submit();
        }
    }
    get payload() {
        const formValues = new Owner(this.formController.values.getValue()).payload;
        if (this.ownerId) {
            return formValues;
        }
        else {
            return Object.assign(Object.assign({}, formValues), { business_id: this.businessId });
        }
    }
    get formTitle() {
        return this.ownerId ? 'Edit Business Owner' : 'Add Business Owner';
    }
    get submitButtonText() {
        return this.ownerId ? 'Update' : 'Add';
    }
    get showRemoveButton() {
        const blankForm = !this.ownerId && this.newFormOpen;
        if (this.ownersLength <= 1) {
            return false;
        }
        else {
            if (blankForm) {
                return true;
            }
            else if (this.ownerId && !this.newFormOpen) {
                return true;
            }
        }
    }
    componentWillLoad() {
        const schemaFactory = identitySchemaByCountry[this.country];
        this.formController = new FormController(schemaFactory('owner', this.allowOptionalFields));
        this.initializeApi();
        this.ownerId && this.getOwner ? this.getData() : this.instantiateOwner({});
    }
    componentDidLoad() {
        this.formController.errors.subscribe((errors) => (this.errors = Object.assign({}, errors)));
    }
    initializeApi() {
        if (!this.authToken) {
            return;
        }
        this.getOwner = makeGetIdentity({
            authToken: this.authToken,
            identityId: this.ownerId,
            service: new IdentityService(),
        });
        this.patchOwner = makePatchIdentity({
            authToken: this.authToken,
            identityId: this.ownerId,
            service: new IdentityService(),
        });
        this.postOwner = makePostIdentity({
            authToken: this.authToken,
            service: new IdentityService(),
        });
    }
    render() {
        return (h(Host, { key: 'b168e9f5a52416984e6a04ab5f0771b63ee28b2e', style: { display: 'block' } }, h("form", { key: 'd22a6aae3f5debd30d87b3bd37c67390a46c4590', onSubmit: this.validateAndSubmit }, h("fieldset", { key: '30597bc1f4983bddbdc0ed45e6be7e715d0b9b8e' }, h("legend", { key: '055ca2b6bbfa4e86591411668eaead3bd0d95ea8', class: "fw-semibold fs-5 w-100", part: heading3 }, this.formTitle), h("br", { key: 'f0d2d9624611ee888ff318ec1525281bf007e346' }), h("div", { key: '2c38a166f681404c2ab303630217e54c15f1e5f2', class: "row gy-3" }, h("owner-form-inputs", { key: '05253624d3d79f0ba7a4ec49b387e252e796e5b6', ownerDefaultValue: this.formController.getInitialValues(), errors: this.errors, formController: this.formController, country: this.country }), h("div", { key: '8e0e67966f047c3f9a4b30f28983f67db2372c0c', class: "d-flex gap-2 justify-content-start" }, h(Button, { key: 'e33368a968efe5faf52a08e36bb2bef215625c4a', variant: "secondary", type: "button", onClick: this.handleRemoveOwner, hidden: !this.showRemoveButton }, "Remove"), h(Button, { key: '7bb79b0624dfb3a8645182432c484f288cc73692', variant: "primary", type: "submit", onClick: this.handleAddOwner, disabled: this.isLoading }, this.submitButtonText))), h("hr", { key: 'ef4f86dd1b1878e92c98e4a826f9fbad808e15b7' })))));
    }
    static get is() { return "owner-form"; }
    static get properties() {
        return {
            "authToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "auth-token"
            },
            "ownerId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "owner-id"
            },
            "businessId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "business-id"
            },
            "allowOptionalFields": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "allow-optional-fields"
            },
            "removeOwner": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(id: string) => void",
                    "resolved": "(id: string) => void",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "newFormOpen": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "new-form-open"
            },
            "ownersLength": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "owners-length"
            },
            "country": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "CountryCode",
                    "resolved": "CountryCode.CAN | CountryCode.USA",
                    "references": {
                        "CountryCode": {
                            "location": "import",
                            "path": "../../../utils/country-codes",
                            "id": "src/utils/country-codes.ts::CountryCode"
                        }
                    }
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "country"
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "formController": {},
            "errors": {},
            "owner": {},
            "getOwner": {},
            "patchOwner": {},
            "postOwner": {}
        };
    }
    static get events() {
        return [{
                "method": "clickEvent",
                "name": "click-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentClickEvent",
                    "resolved": "ComponentClickEvent",
                    "references": {
                        "ComponentClickEvent": {
                            "location": "import",
                            "path": "../../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentClickEvent"
                        }
                    }
                }
            }, {
                "method": "errorEvent",
                "name": "error-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentErrorEvent",
                    "resolved": "ComponentErrorEvent",
                    "references": {
                        "ComponentErrorEvent": {
                            "location": "import",
                            "path": "../../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentErrorEvent"
                        }
                    }
                }
            }, {
                "method": "formLoading",
                "name": "formLoading",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }, {
                "method": "ownerSubmitted",
                "name": "ownerSubmitted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "returnOwnerData": {
                "complexType": {
                    "signature": "() => Promise<string>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<string>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "getOwnershipPercentage": {
                "complexType": {
                    "signature": "() => Promise<string | null>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<string>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "setOwnershipPercentageError": {
                "complexType": {
                    "signature": "(message: string) => Promise<void>",
                    "parameters": [{
                            "name": "message",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "validate": {
                "complexType": {
                    "signature": "() => Promise<boolean>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<boolean>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "submit": {
                "complexType": {
                    "signature": "() => Promise<boolean>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<boolean>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "validateAndSubmit": {
                "complexType": {
                    "signature": "(event: any) => Promise<void>",
                    "parameters": [{
                            "name": "event",
                            "type": "any",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get watchers() {
        return [{
                "propName": "isLoading",
                "methodName": "loadingWatcher"
            }];
    }
}
