import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../../../api/ComponentError";
import { makeGetBusiness, makePatchBusiness } from "../payment-provisioning-actions";
import { BusinessService } from "../../../../api/services/business.service";
import { Representative } from "../../../../api/Identity";
import { FormController } from "../../../../ui-components/form/form";
import { identitySchemaByCountry } from "../../schemas/business-identity-schema";
import { PaymentProvisioningLoading } from "../payment-provisioning-loading";
import { BusinessFormStep } from "../../utils";
export class BusinessRepresentativeFormStep {
    constructor() {
        this.errors = {};
        this.representative = {};
        this.isLoading = false;
        this.getData = () => {
            if (!this.getBusiness || !this.formController)
                return;
            this.formLoading.emit(true);
            this.isLoading = true;
            this.getBusiness({
                onSuccess: (response) => {
                    this.representative = new Representative(response.data.representative || {});
                    this.representative.address.country = this.country;
                    this.formController.setInitialValues(Object.assign({}, this.representative));
                },
                onError: ({ error, code, severity }) => {
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.formLoading.emit(false);
                    this.isLoading = false;
                }
            });
        };
        this.sendData = (onSuccess) => {
            let submittedData;
            this.formLoading.emit(true);
            this.patchBusiness({
                payload: this.patchPayload,
                onSuccess: (response) => {
                    submittedData = response;
                    onSuccess();
                },
                onError: ({ error, code, severity }) => {
                    submittedData = error;
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity
                    });
                },
                final: () => {
                    this.stepCompleteEvent.emit({ response: submittedData, formStep: BusinessFormStep.representative });
                    this.formLoading.emit(false);
                }
            });
        };
    }
    propChanged() {
        this.initializeApi();
        this.getData();
    }
    async validateAndSubmit({ onSuccess }) {
        this.formController.validateAndSubmit(() => this.sendData(onSuccess));
    }
    componentWillLoad() {
        this.initializeApi();
        this.initializeForm();
    }
    initializeApi() {
        if (this.authToken && this.businessId) {
            this.getBusiness = makeGetBusiness({
                authToken: this.authToken,
                businessId: this.businessId,
                service: new BusinessService()
            });
            this.patchBusiness = makePatchBusiness({
                authToken: this.authToken,
                businessId: this.businessId,
                service: new BusinessService()
            });
        }
        else {
            this.errorEvent.emit({
                message: 'Missing required props',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    initializeForm() {
        const schemaFactory = identitySchemaByCountry[this.country];
        if (!schemaFactory) {
            this.errorEvent.emit({
                message: 'Missing schema for selected country',
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
            return;
        }
        this.formController = new FormController(schemaFactory('representative', this.allowOptionalFields));
        this.getData();
    }
    componentDidLoad() {
        if (!this.formController)
            return;
        this.formController.errors.subscribe(errors => {
            this.errors = Object.assign({}, errors);
        });
    }
    get patchPayload() {
        const formValues = new Representative(this.formController.values.getValue()).payload;
        return { representative: formValues };
    }
    render() {
        if (!this.formController || this.isLoading) {
            return (h(PaymentProvisioningLoading, null));
        }
        return (h("business-representative-form-inputs", { representativeDefaultValue: this.formController.getInitialValues(), errors: this.errors, formController: this.formController, country: this.country }));
    }
    static get is() { return "business-representative-form-step"; }
    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"
            },
            "businessId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "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"
            },
            "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": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "country"
            }
        };
    }
    static get states() {
        return {
            "getBusiness": {},
            "patchBusiness": {},
            "formController": {},
            "errors": {},
            "representative": {},
            "isLoading": {}
        };
    }
    static get events() {
        return [{
                "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": "stepCompleteEvent",
                "name": "complete-form-step-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentFormStepCompleteEvent",
                    "resolved": "ComponentFormStepCompleteEvent",
                    "references": {
                        "ComponentFormStepCompleteEvent": {
                            "location": "import",
                            "path": "../../../../api/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentFormStepCompleteEvent"
                        }
                    }
                }
            }, {
                "method": "formLoading",
                "name": "formLoading",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "validateAndSubmit": {
                "complexType": {
                    "signature": "({ onSuccess }: { onSuccess: any; }) => Promise<void>",
                    "parameters": [{
                            "name": "__0",
                            "type": "{ onSuccess: any; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get watchers() {
        return [{
                "propName": "authToken",
                "methodName": "propChanged"
            }, {
                "propName": "businessId",
                "methodName": "propChanged"
            }];
    }
}
;
