import { __decorate, __metadata } from 'tslib';
import * as i0 from '@angular/core';
import { Component, Input, EventEmitter, Output, NgModule } from '@angular/core';
import * as i3$1 from '@aztrix/helpers';
import { getPropertiesOfType, parsePropertiesFromStripeCustomerInfo, updateBillingForm, CustomValidators, PropertyFormControl, parseStripeCustomerInfoFromBillingForm, HelperPipesModule } from '@aztrix/helpers';
import { PropertyType } from '@aztrix/models';
import * as i1 from '@aztrix/sdk';
import { StripeCustomerInfoRepresentation, ProfileService, PaymentsService } from '@aztrix/sdk';
import { FormGroup, FormControl } from '@ngneat/reactive-forms';
import { UntilDestroy } from '@ngneat/until-destroy';
import { BehaviorSubject, first as first$1 } from 'rxjs';
import { map, shareReplay, first } from 'rxjs/operators';
import * as i2 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i3 from '@aztrix/components/property-edit';
import { PropertyEditModule } from '@aztrix/components/property-edit';
import * as i4 from '@aztrix/components/selection-buttons';
import { SelectionButtonsModule } from '@aztrix/components/selection-buttons';
import * as i5 from '@aztrix/components/snackbar';
import { SnackbarModule } from '@aztrix/components/snackbar';
import * as i6 from '@aztrix/components/spinner';
import { SpinnerModule } from '@aztrix/components/spinner';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import * as i5$1 from '@aztrix/components/button';
import { ButtonModule } from '@aztrix/components/button';
import { PaymentMethodModule } from '@aztrix/components/payment-method';
import { IconsModule } from '@aztrix/icons';
import * as i2$1 from '@aztrix/components/overlay';

let EditBillingInformationComponent = class EditBillingInformationComponent {
    constructor(_profileService, _paymentService) {
        this._profileService = _profileService;
        this._paymentService = _paymentService;
        this.form = new FormGroup({});
        this.propertyType = PropertyType;
        this._loading$ = new BehaviorSubject({
            profile: true,
            stripe: true,
        });
        this.loading$ = this._loading$.pipe(map(({ profile, stripe }) => profile || stripe));
        this.snackBar$ = new BehaviorSubject(null);
        this.color$ = this.snackBar$.pipe(map((snackbar) => {
            switch (snackbar?.color) {
                case 'green':
                    return 'green';
                case 'red':
                    return 'red';
                case 'grey':
                    return 'grey';
                case 'orange':
                    return 'orange';
                default:
                    return 'green';
            }
        }));
        this._myProfile$ = this._profileService.getMeProfile().pipe(shareReplay(1));
        this.autocompleteLegalId$ = this._myProfile$.pipe(map((profile) => getPropertiesOfType(profile, PropertyType.LEGAL_ID)));
        this.autocompleteLegalName$ = this._myProfile$.pipe(map((profile) => getPropertiesOfType(profile, PropertyType.LEGAL_NAME)));
        this.autocompleteAddress$ = this._myProfile$.pipe(map((profile) => getPropertiesOfType(profile, PropertyType.ADDRESS)));
        this.autocompleteEmail$ = this._myProfile$.pipe(map((profile) => getPropertiesOfType(profile, PropertyType.EMAIL)));
    }
    ngOnChanges(changes) {
        if (changes.form && this.form) {
            this._loading$.next({ profile: true, stripe: true });
            this._initForm();
            this._myProfile$.pipe(first()).subscribe((profile) => {
                this.form.get('customerType').setValue(profile.profileContext);
                this._selectionChange(profile.profileContext);
                this._loading$.next({ profile: false, stripe: this._loading$.value.stripe });
            });
            this._paymentService
                .getStripeCustomerInfo()
                .pipe(first())
                .subscribe({
                error: (error) => {
                    if (error.error !== 'CUSTOMER_NOT_FOUND') {
                        this.snackBar$.next({
                            message: 'error.500.body',
                            color: 'red',
                        });
                    }
                    this._loading$.next({ profile: this._loading$.value.profile, stripe: false });
                },
                next: (stripeCustomerInfo) => {
                    const properties = parsePropertiesFromStripeCustomerInfo(stripeCustomerInfo);
                    if (stripeCustomerInfo.customerType) {
                        this.customerTypeControl.setValue(stripeCustomerInfo.customerType);
                    }
                    updateBillingForm(properties, this.form);
                    this._loading$.next({ profile: this._loading$.value.profile, stripe: false });
                },
            });
        }
    }
    ngOnInit() {
        this.customerTypeControl?.valueChanges.subscribe((customerType) => {
            this._selectionChange(customerType);
        });
    }
    get propertiesControl() {
        return this.nameControl.get('properties');
    }
    _selectionChange(customerType) {
        if (customerType === StripeCustomerInfoRepresentation.CustomerTypeEnum.INDIVIDUAL) {
            this._addControl(PropertyType.NAME, [
                CustomValidators.propertyRequired,
                CustomValidators.propertyValid,
            ]);
            // before removing, keep the control data
            this._legalIdControl = this.legalIdControl;
            this._legalNameControl = this.legalNameControl;
            this._removeControl(PropertyType.LEGAL_NAME);
            this._removeControl(PropertyType.LEGAL_ID);
        }
        else {
            this._addControl(PropertyType.LEGAL_ID, [CustomValidators.propertyValid]);
            this._addControl(PropertyType.LEGAL_NAME, [
                CustomValidators.propertyRequired,
                CustomValidators.propertyValid,
            ]);
            this._nameControl = this.nameControl;
            this._removeControl(PropertyType.NAME);
        }
        this._setControls();
    }
    _addControl(propertyType, validatorsFn) {
        const existingControl = this._existingControlByType(propertyType);
        const control = existingControl ?? PropertyFormControl.createByType(propertyType, validatorsFn);
        this.form.setControl(propertyType, control);
    }
    _removeControl(propertyType) {
        this.form.removeControl(propertyType);
    }
    _existingControlByType(type) {
        switch (type) {
            case PropertyType.NAME:
                return this._nameControl;
            case PropertyType.LEGAL_NAME:
                return this._legalNameControl;
            case PropertyType.LEGAL_ID:
                return this._legalIdControl;
            default:
                return undefined;
        }
    }
    _initForm() {
        this.form.setControl('customerType', new FormControl(StripeCustomerInfoRepresentation.CustomerTypeEnum.INDIVIDUAL));
        this.form.setControl(PropertyType.ADDRESS, PropertyFormControl.createByType(PropertyType.ADDRESS, [
            CustomValidators.propertyRequired,
            CustomValidators.propertyValid,
        ]));
        this.form.setControl(PropertyType.EMAIL, PropertyFormControl.createByType(PropertyType.EMAIL, [
            CustomValidators.propertyRequired,
            CustomValidators.propertyValid,
        ]));
        this._setControls();
    }
    _setControls() {
        this.nameControl = this._getControlByType(PropertyType.NAME);
        this.legalNameControl = this._getControlByType(PropertyType.LEGAL_NAME);
        this.legalIdControl = this._getControlByType(PropertyType.LEGAL_ID);
        this.addressControl = this._getControlByType(PropertyType.ADDRESS);
        this.emailControl = this._getControlByType(PropertyType.EMAIL);
        this.customerTypeControl = this.form.get('customerType');
    }
    _getControlByType(type) {
        return this.form.get(type);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationComponent, deps: [{ token: i1.ProfileService }, { token: i1.PaymentsService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "17.3.12", type: EditBillingInformationComponent, selector: "ax-edit-billing-information", inputs: { form: "form" }, usesOnChanges: true, ngImport: i0, template: "<ng-template #content>\n  <ax-profile-context-selection-buttons\n    *ngIf=\"customerTypeControl\"\n    [form]=\"customerTypeControl\"\n    [fullWidth]=\"true\"\n  ></ax-profile-context-selection-buttons>\n\n  <ax-property-edit\n    *ngIf=\"legalIdControl\"\n    [form]=\"legalIdControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteLegalId$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n  ></ax-property-edit>\n  <ax-name-edit *ngIf=\"nameControl\" [form]=\"propertiesControl\" [required]=\"true\"></ax-name-edit>\n  <ax-property-edit\n    *ngIf=\"legalNameControl\"\n    [form]=\"legalNameControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteLegalName$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n    [required]=\"true\"\n  ></ax-property-edit>\n  <ax-property-edit\n    *ngIf=\"addressControl\"\n    [form]=\"addressControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteAddress$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n    [required]=\"true\"\n  ></ax-property-edit>\n  <ax-property-edit\n    *ngIf=\"emailControl\"\n    [form]=\"emailControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteEmail$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n    [required]=\"true\"\n  ></ax-property-edit>\n</ng-template>\n\n<ax-snackbar [color]=\"(color$ | async) || 'green'\" [open]=\"!!(snackBar$ | async)\">\n  {{ (snackBar$ | async)?.message | translate: (snackBar$ | async)?.messageOpts }}\n</ax-snackbar>\n\n<ax-spinner *ngIf=\"loading$ | async; else content\"></ax-spinner>\n", styles: [""], dependencies: [{ kind: "directive", type: i2.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i3.PropertyEditComponent, selector: "ax-property-edit", inputs: ["isIndividual", "isProposalSubscribeForm"] }, { kind: "component", type: i3.NameEditComponent, selector: "ax-name-edit", inputs: ["form", "name", "autofocus", "customLabel", "required", "expanded", "hint", "readonly"] }, { kind: "component", type: i4.ProfileContextSelectionButtonsComponent, selector: "ax-profile-context-selection-buttons", inputs: ["form", "fullWidth"] }, { kind: "component", type: i5.SnackbarComponent, selector: "ax-snackbar", inputs: ["type", "timeout", "dismissible", "open", "icon", "color"], outputs: ["didClose"] }, { kind: "component", type: i6.SpinnerComponent, selector: "ax-spinner" }, { kind: "pipe", type: i2.AsyncPipe, name: "async" }, { kind: "pipe", type: i3$1.TranslatePipe, name: "translate" }] }); }
};
EditBillingInformationComponent = __decorate([
    UntilDestroy(),
    __metadata("design:paramtypes", [ProfileService,
        PaymentsService])
], EditBillingInformationComponent);
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-edit-billing-information', template: "<ng-template #content>\n  <ax-profile-context-selection-buttons\n    *ngIf=\"customerTypeControl\"\n    [form]=\"customerTypeControl\"\n    [fullWidth]=\"true\"\n  ></ax-profile-context-selection-buttons>\n\n  <ax-property-edit\n    *ngIf=\"legalIdControl\"\n    [form]=\"legalIdControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteLegalId$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n  ></ax-property-edit>\n  <ax-name-edit *ngIf=\"nameControl\" [form]=\"propertiesControl\" [required]=\"true\"></ax-name-edit>\n  <ax-property-edit\n    *ngIf=\"legalNameControl\"\n    [form]=\"legalNameControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteLegalName$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n    [required]=\"true\"\n  ></ax-property-edit>\n  <ax-property-edit\n    *ngIf=\"addressControl\"\n    [form]=\"addressControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteAddress$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n    [required]=\"true\"\n  ></ax-property-edit>\n  <ax-property-edit\n    *ngIf=\"emailControl\"\n    [form]=\"emailControl\"\n    [autocomplete]=\"true\"\n    [autocompleteProperties]=\"(autocompleteEmail$ | async) || undefined\"\n    autocompleteAttr=\"off\"\n    [required]=\"true\"\n  ></ax-property-edit>\n</ng-template>\n\n<ax-snackbar [color]=\"(color$ | async) || 'green'\" [open]=\"!!(snackBar$ | async)\">\n  {{ (snackBar$ | async)?.message | translate: (snackBar$ | async)?.messageOpts }}\n</ax-snackbar>\n\n<ax-spinner *ngIf=\"loading$ | async; else content\"></ax-spinner>\n" }]
        }], ctorParameters: () => [{ type: i1.ProfileService }, { type: i1.PaymentsService }], propDecorators: { form: [{
                type: Input
            }] } });

class EditBillingInformationUpdateComponent {
    constructor(_paymentsService, _overlayService, _translateService) {
        this._paymentsService = _paymentsService;
        this._overlayService = _overlayService;
        this._translateService = _translateService;
        this.paymentInfoForm = new FormGroup({});
        this.didClickSave = new EventEmitter();
        this.errorSnackbar$ = new BehaviorSubject(null);
    }
    save() {
        this._paymentsService
            .setStripeCustomerInfo(parseStripeCustomerInfoFromBillingForm(this.paymentInfoForm))
            .pipe(first$1())
            .subscribe({
            error: (error) => {
                if (error.error === 'INVALID_TAX_ID') {
                    this.errorSnackbar$.next({
                        message: 'property.validation.invalid',
                        options: {
                            propertyType: this._translateService.instant(`property.${PropertyType.LEGAL_ID}.label`),
                        },
                    });
                }
                else {
                    this.errorSnackbar$.next({
                        message: 'error.default.title',
                    });
                }
            },
            next: () => this.didClickSave.emit(),
        });
    }
    cancel() {
        this._overlayService.closeModal();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationUpdateComponent, deps: [{ token: i1.PaymentsService }, { token: i2$1.OverlayService }, { token: i3$1.TranslateService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "17.3.12", type: EditBillingInformationUpdateComponent, selector: "ax-edit-billing-information-update", inputs: { paymentInfoForm: "paymentInfoForm" }, outputs: { didClickSave: "didClickSave" }, ngImport: i0, template: "<ax-snackbar\n  *ngIf=\"(errorSnackbar$ | async) !== null\"\n  [dismissible]=\"false\"\n  color=\"red\"\n  [timeout]=\"10000\"\n>\n  {{ (errorSnackbar$ | async)?.message | translate: (errorSnackbar$ | async)?.options }}\n</ax-snackbar>\n\n<ax-edit-billing-information [form]=\"paymentInfoForm\"></ax-edit-billing-information>\n\n<div class=\"h-button-wrapper\">\n  <button class=\"button\" axButton color=\"primary\" (click)=\"cancel()\">\n    {{ 'label.cancel' | translate }}\n  </button>\n\n  <button class=\"button\" axButton filled color=\"primary\" (click)=\"save()\">\n    {{ 'label.save' | translate }}\n  </button>\n</div>\n", styles: [":host{display:block;padding:1rem}\n"], dependencies: [{ kind: "directive", type: i2.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i5$1.ButtonDirective, selector: "[axButton]", inputs: ["color", "labelHideMobile", "smallButton", "bigButton", "fullWidth", "filled", "outline", "icon-button", "hoverLabel", "hover", "lowercase", "disabled"] }, { kind: "component", type: i5.SnackbarComponent, selector: "ax-snackbar", inputs: ["type", "timeout", "dismissible", "open", "icon", "color"], outputs: ["didClose"] }, { kind: "component", type: EditBillingInformationComponent, selector: "ax-edit-billing-information", inputs: ["form"] }, { kind: "pipe", type: i2.AsyncPipe, name: "async" }, { kind: "pipe", type: i3$1.TranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationUpdateComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-edit-billing-information-update', template: "<ax-snackbar\n  *ngIf=\"(errorSnackbar$ | async) !== null\"\n  [dismissible]=\"false\"\n  color=\"red\"\n  [timeout]=\"10000\"\n>\n  {{ (errorSnackbar$ | async)?.message | translate: (errorSnackbar$ | async)?.options }}\n</ax-snackbar>\n\n<ax-edit-billing-information [form]=\"paymentInfoForm\"></ax-edit-billing-information>\n\n<div class=\"h-button-wrapper\">\n  <button class=\"button\" axButton color=\"primary\" (click)=\"cancel()\">\n    {{ 'label.cancel' | translate }}\n  </button>\n\n  <button class=\"button\" axButton filled color=\"primary\" (click)=\"save()\">\n    {{ 'label.save' | translate }}\n  </button>\n</div>\n", styles: [":host{display:block;padding:1rem}\n"] }]
        }], ctorParameters: () => [{ type: i1.PaymentsService }, { type: i2$1.OverlayService }, { type: i3$1.TranslateService }], propDecorators: { paymentInfoForm: [{
                type: Input
            }], didClickSave: [{
                type: Output
            }] } });

class EditBillingInformationModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationModule, declarations: [EditBillingInformationComponent, EditBillingInformationUpdateComponent], imports: [CommonModule,
            HelperPipesModule,
            IconsModule,
            PropertyEditModule,
            FormsModule,
            ReactiveFormsModule,
            PaymentMethodModule,
            SelectionButtonsModule,
            ButtonModule,
            SnackbarModule,
            SpinnerModule], exports: [EditBillingInformationComponent, EditBillingInformationUpdateComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationModule, imports: [CommonModule,
            HelperPipesModule,
            IconsModule,
            PropertyEditModule,
            FormsModule,
            ReactiveFormsModule,
            PaymentMethodModule,
            SelectionButtonsModule,
            ButtonModule,
            SnackbarModule,
            SpinnerModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: EditBillingInformationModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [EditBillingInformationComponent, EditBillingInformationUpdateComponent],
                    imports: [
                        CommonModule,
                        HelperPipesModule,
                        IconsModule,
                        PropertyEditModule,
                        FormsModule,
                        ReactiveFormsModule,
                        PaymentMethodModule,
                        SelectionButtonsModule,
                        ButtonModule,
                        SnackbarModule,
                        SpinnerModule,
                    ],
                    exports: [EditBillingInformationComponent, EditBillingInformationUpdateComponent],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { EditBillingInformationComponent, EditBillingInformationModule, EditBillingInformationUpdateComponent };
//# sourceMappingURL=aztrix-components-edit-billing-information.mjs.map
