import * as i0 from '@angular/core';
import { EventEmitter, Component, Input, Output, NgModule } from '@angular/core';
import { Validators, ReactiveFormsModule } from '@angular/forms';
import * as i2 from '@aztrix/components/overlay';
import * as i9 from '@aztrix/helpers';
import { PropertyFormControl, CustomValidators, isOfType, HelperPipesModule } from '@aztrix/helpers';
import * as i1 from '@aztrix/sdk';
import { PropertyRepresentation, ProfilePropertyRepresentation, ContextTypeRepresentation } from '@aztrix/sdk';
import { FormControl } from '@ngneat/reactive-forms';
import { BehaviorSubject, ReplaySubject, first, switchMap, tap, map, of } from 'rxjs';
import * as i3 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i4 from '@aztrix/components/property-edit';
import { PropertyEditModule } from '@aztrix/components/property-edit';
import * as i5 from '@aztrix/components/button';
import { ButtonModule } from '@aztrix/components/button';
import * as i6 from '@aztrix/components/snackbar';
import { SnackbarModule } from '@aztrix/components/snackbar';
import * as i7 from '@aztrix/components/password-edit';
import { PasswordEditModule } from '@aztrix/components/password-edit';
import * as i8 from '@aztrix/components/property-otp-verification';
import { PropertyOtpVerificationModule } from '@aztrix/components/property-otp-verification';

class ChangeLoginValueStepperComponent {
    constructor(_profile, _contexts, _properties, _settings, _overlay) {
        this._profile = _profile;
        this._contexts = _contexts;
        this._properties = _properties;
        this._settings = _settings;
        this._overlay = _overlay;
        this.loginValueChanged = new EventEmitter();
        this.step = 1;
        this.loading$ = new BehaviorSubject(false);
        this.propertyForm = (PropertyFormControl.createByType(PropertyRepresentation.TypeEnum.EMAIL, [
            CustomValidators.propertyRequired,
            CustomValidators.propertyValid,
        ]));
        this.profileProperty$ = new ReplaySubject(0);
        this.passwordForm = new FormControl('', [Validators.required, Validators.minLength(8)]);
        this.error$ = new BehaviorSubject(null);
        this.accountProperties$ = new BehaviorSubject([]);
        this.contextId$ = new ReplaySubject(0);
        this.verification = (code, verificationValue) => {
            return this.accountProperties$.pipe(first(), switchMap((properties) => {
                const property = properties.find((property) => property.value === verificationValue);
                return this._properties.verifyPropertyWithOtp(property.id, code);
            }), tap((property) => this.profileProperty$.next(property)));
        };
        this.retryVerification = (verificationValue) => {
            return this.accountProperties$.pipe(first(), switchMap((properties) => {
                const property = properties.find((property) => property.value === verificationValue);
                return this._properties.requestVerificationForProperty(property.id);
            }));
        };
    }
    ngOnInit() {
        this._getAccountProperties$()
            .pipe(first())
            .subscribe((properties) => {
            const property = properties.find((property) => property.value === this.currentloginValue);
            this.profileProperty$.next(property);
            PropertyFormControl.update(this.propertyForm, property, [
                CustomValidators.propertyRequired,
                CustomValidators.propertyValid,
            ]);
        });
    }
    continue() {
        this.error$.next(null);
        this.loading$.next(true);
        if (this.propertyForm.valid && this.propertyForm.value.value !== this.currentloginValue) {
            this.accountProperties$
                .pipe(first(), map((properties) => properties.find((property) => property.value === this.propertyForm.value.value)), switchMap((property) => {
                if (property) {
                    return of(property);
                }
                else {
                    return this.contextId$.pipe(first(), switchMap((contextId) => this._contexts.addProperty(contextId, { ...this.propertyForm.value, id: undefined })), switchMap((contextProperty) => this._getAccountProperties$().pipe(map((property) => property.find((property) => property.id === contextProperty.id)))));
                }
            }))
                .subscribe((property) => {
                this.profileProperty$.next(property);
                this.step = this.step + 1;
                if (property.verification === ProfilePropertyRepresentation.VerificationEnum.VERIFIED) {
                    this.step = this.step + 1;
                }
                this.loading$.next(false);
            });
        }
        else {
            this.loading$.next(false);
            this._overlay.closeModal();
        }
    }
    verificationComplete() {
        this.step = this.step + 1;
    }
    updateLoginValue() {
        this.loading$.next(true);
        if (this.passwordForm.valid) {
            this.profileProperty$
                .pipe(first(), switchMap((profileProperty) => this._settings.setLogin({
                propertyId: profileProperty.id,
                password: this.passwordForm.value,
            })))
                .subscribe({
                next: (settings) => {
                    this.loading$.next(false);
                    this.loginValueChanged.emit(settings);
                },
                error: (error) => {
                    this.error$.next(error.error);
                    this.loading$.next(false);
                },
            });
        }
        else {
            this.loading$.next(false);
        }
    }
    _getAccountProperties$() {
        return this._profile.getMeProfile('FULL').pipe(tap((profile) => {
            const contextId = profile.propertyContexts.find((context) => context.type === ContextTypeRepresentation.NameEnum.PERSONAL).id;
            this.contextId$.next(contextId);
        }), map((profile) => profile.propertyContexts
            .filter((context) => !isOfType(context, ContextTypeRepresentation.NameEnum.GROUP, ContextTypeRepresentation.NameEnum.PROPOSAL, ContextTypeRepresentation.NameEnum.MISC))
            .flatMap((context) => context.properties)
            .filter((property) => property.type === ProfilePropertyRepresentation.TypeEnum.EMAIL)), tap((properties) => this.accountProperties$.next(properties)));
    }
}
ChangeLoginValueStepperComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChangeLoginValueStepperComponent, deps: [{ token: i1.ProfileService }, { token: i1.ContextsService }, { token: i1.PropertiesService }, { token: i1.SettingsService }, { token: i2.OverlayService }], target: i0.ɵɵFactoryTarget.Component });
ChangeLoginValueStepperComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.1.5", type: ChangeLoginValueStepperComponent, selector: "ax-change-login-value-stepper", inputs: { currentloginValue: "currentloginValue" }, outputs: { loginValueChanged: "loginValueChanged" }, ngImport: i0, template: "<ng-container *ngIf=\"step === 1\">\n  <p>{{ 'settings.account.credentials.login.modal.section.title' | translate }}</p>\n  <ax-property-edit\n    *ngIf=\"propertyForm?.value\"\n    [form]=\"propertyForm\"\n    [autofocus]=\"false\"\n    [required]=\"true\"\n    [autocompleteProperties]=\"accountProperties$ | async\"\n  ></ax-property-edit>\n\n  <div class=\"button-wrapper\">\n    <ax-button\n      filled\n      color=\"primary\"\n      [loading]=\"loading$ | async\"\n      [disabled]=\"loading$ | async\"\n      (click)=\"continue()\"\n    >\n      {{\n        currentloginValue === propertyForm.value.value\n          ? ('label.close' | translate)\n          : ('label.next' | translate)\n      }}\n    </ax-button>\n  </div>\n</ng-container>\n<ng-container *ngIf=\"step === 2\">\n  <ax-property-otp-verification\n    [property]=\"profileProperty$ | async\"\n    [canChangeValue]=\"true\"\n    (verificationComplete)=\"verificationComplete()\"\n  >\n  </ax-property-otp-verification>\n</ng-container>\n\n<ng-container *ngIf=\"step === 3\">\n  <ax-snackbar *ngIf=\"error$ | async\" [dismissible]=\"false\" color=\"red\">\n    <ng-container [ngSwitch]=\"error$ | async\">\n      <span *ngSwitchCase=\"'FORBIDDEN'\">{{ 'error.FORBIDDEN.message' | translate }}</span>\n      <span *ngSwitchCase=\"'LOGIN_INVALID_PASSWORD'\">{{\n        'error.login.invalid.password' | translate\n      }}</span>\n      <span *ngSwitchCase=\"'LOGIN_ALREADY_REGISTERED'\">{{\n        'register.already.exists'\n          | translate\n            : {\n                loginValue: (profileProperty$ | async)?.value,\n                propertyType:\n                  'property.' + (profileProperty$ | async)?.type + '.label' | translate | lowercase\n              }\n      }}</span>\n      <span *ngSwitchDefault>{{ 'error.default.title' | translate }}</span>\n    </ng-container>\n  </ax-snackbar>\n\n  <p>{{ 'settings.account.credentials.password.modal.confirm.title' | translate }}</p>\n\n  <ax-password-edit\n    [form]=\"passwordForm\"\n    [label]=\"'label.password' | translate\"\n    showToggle=\"true\"\n    autocomplete=\"password\"\n  ></ax-password-edit>\n  <div class=\"button-wrapper\">\n    <ax-button [loading]=\"loading$ | async\" [disabled]=\"loading$ | async\" (click)=\"step = 1\">\n      {{ 'label.back' | translate }}\n    </ax-button>\n    <ax-button\n      filled\n      color=\"primary\"\n      [loading]=\"loading$ | async\"\n      [disabled]=\"loading$ | async\"\n      (click)=\"updateLoginValue()\"\n    >\n      {{ 'label.confirm' | translate }}\n    </ax-button>\n  </div>\n</ng-container>\n", styles: [":host{display:block;padding:1rem}:host ax-property-otp-verification{padding:0}.button-wrapper{display:flex;justify-content:flex-end;gap:1rem;padding-top:.75rem}p{margin-top:0}\n"], dependencies: [{ kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i3.NgSwitch, selector: "[ngSwitch]", inputs: ["ngSwitch"] }, { kind: "directive", type: i3.NgSwitchCase, selector: "[ngSwitchCase]", inputs: ["ngSwitchCase"] }, { kind: "directive", type: i3.NgSwitchDefault, selector: "[ngSwitchDefault]" }, { kind: "component", type: i4.PropertyEditComponent, selector: "ax-property-edit", inputs: ["isIndividual", "isProposalSubscribeForm"] }, { kind: "component", type: i5.ButtonComponent, selector: "ax-button" }, { kind: "component", type: i6.SnackbarComponent, selector: "ax-snackbar", inputs: ["type", "timeout", "dismissible", "open", "icon", "color"], outputs: ["didClose"] }, { kind: "component", type: i7.PasswordEditComponent, selector: "ax-password-edit", inputs: ["username", "showToggle", "forgotPasswordHint", "saveInPasswordManager", "minLength"] }, { kind: "component", type: i8.PropertyOtpVerificationComponent, selector: "ax-property-otp-verification", inputs: ["property", "canChangeValue"], outputs: ["propertyUpdate", "verificationComplete"] }, { kind: "pipe", type: i3.AsyncPipe, name: "async" }, { kind: "pipe", type: i3.LowerCasePipe, name: "lowercase" }, { kind: "pipe", type: i9.TranslatePipe, name: "translate" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChangeLoginValueStepperComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-change-login-value-stepper', template: "<ng-container *ngIf=\"step === 1\">\n  <p>{{ 'settings.account.credentials.login.modal.section.title' | translate }}</p>\n  <ax-property-edit\n    *ngIf=\"propertyForm?.value\"\n    [form]=\"propertyForm\"\n    [autofocus]=\"false\"\n    [required]=\"true\"\n    [autocompleteProperties]=\"accountProperties$ | async\"\n  ></ax-property-edit>\n\n  <div class=\"button-wrapper\">\n    <ax-button\n      filled\n      color=\"primary\"\n      [loading]=\"loading$ | async\"\n      [disabled]=\"loading$ | async\"\n      (click)=\"continue()\"\n    >\n      {{\n        currentloginValue === propertyForm.value.value\n          ? ('label.close' | translate)\n          : ('label.next' | translate)\n      }}\n    </ax-button>\n  </div>\n</ng-container>\n<ng-container *ngIf=\"step === 2\">\n  <ax-property-otp-verification\n    [property]=\"profileProperty$ | async\"\n    [canChangeValue]=\"true\"\n    (verificationComplete)=\"verificationComplete()\"\n  >\n  </ax-property-otp-verification>\n</ng-container>\n\n<ng-container *ngIf=\"step === 3\">\n  <ax-snackbar *ngIf=\"error$ | async\" [dismissible]=\"false\" color=\"red\">\n    <ng-container [ngSwitch]=\"error$ | async\">\n      <span *ngSwitchCase=\"'FORBIDDEN'\">{{ 'error.FORBIDDEN.message' | translate }}</span>\n      <span *ngSwitchCase=\"'LOGIN_INVALID_PASSWORD'\">{{\n        'error.login.invalid.password' | translate\n      }}</span>\n      <span *ngSwitchCase=\"'LOGIN_ALREADY_REGISTERED'\">{{\n        'register.already.exists'\n          | translate\n            : {\n                loginValue: (profileProperty$ | async)?.value,\n                propertyType:\n                  'property.' + (profileProperty$ | async)?.type + '.label' | translate | lowercase\n              }\n      }}</span>\n      <span *ngSwitchDefault>{{ 'error.default.title' | translate }}</span>\n    </ng-container>\n  </ax-snackbar>\n\n  <p>{{ 'settings.account.credentials.password.modal.confirm.title' | translate }}</p>\n\n  <ax-password-edit\n    [form]=\"passwordForm\"\n    [label]=\"'label.password' | translate\"\n    showToggle=\"true\"\n    autocomplete=\"password\"\n  ></ax-password-edit>\n  <div class=\"button-wrapper\">\n    <ax-button [loading]=\"loading$ | async\" [disabled]=\"loading$ | async\" (click)=\"step = 1\">\n      {{ 'label.back' | translate }}\n    </ax-button>\n    <ax-button\n      filled\n      color=\"primary\"\n      [loading]=\"loading$ | async\"\n      [disabled]=\"loading$ | async\"\n      (click)=\"updateLoginValue()\"\n    >\n      {{ 'label.confirm' | translate }}\n    </ax-button>\n  </div>\n</ng-container>\n", styles: [":host{display:block;padding:1rem}:host ax-property-otp-verification{padding:0}.button-wrapper{display:flex;justify-content:flex-end;gap:1rem;padding-top:.75rem}p{margin-top:0}\n"] }]
        }], ctorParameters: function () { return [{ type: i1.ProfileService }, { type: i1.ContextsService }, { type: i1.PropertiesService }, { type: i1.SettingsService }, { type: i2.OverlayService }]; }, propDecorators: { currentloginValue: [{
                type: Input
            }], loginValueChanged: [{
                type: Output
            }] } });

class ChangeLoginValueStepperModule {
}
ChangeLoginValueStepperModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChangeLoginValueStepperModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
ChangeLoginValueStepperModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.5", ngImport: i0, type: ChangeLoginValueStepperModule, declarations: [ChangeLoginValueStepperComponent], imports: [CommonModule,
        ReactiveFormsModule,
        HelperPipesModule,
        PropertyEditModule,
        ButtonModule,
        SnackbarModule,
        PasswordEditModule,
        PropertyOtpVerificationModule], exports: [ChangeLoginValueStepperComponent] });
ChangeLoginValueStepperModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChangeLoginValueStepperModule, imports: [CommonModule,
        ReactiveFormsModule,
        HelperPipesModule,
        PropertyEditModule,
        ButtonModule,
        SnackbarModule,
        PasswordEditModule,
        PropertyOtpVerificationModule] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChangeLoginValueStepperModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [ChangeLoginValueStepperComponent],
                    imports: [
                        CommonModule,
                        ReactiveFormsModule,
                        HelperPipesModule,
                        PropertyEditModule,
                        ButtonModule,
                        SnackbarModule,
                        PasswordEditModule,
                        PropertyOtpVerificationModule,
                    ],
                    exports: [ChangeLoginValueStepperComponent],
                }]
        }] });

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

export { ChangeLoginValueStepperComponent, ChangeLoginValueStepperModule };
//# sourceMappingURL=aztrix-components-change-login-value-stepper.mjs.map
//# sourceMappingURL=aztrix-components-change-login-value-stepper.mjs.map
