import { Component, EventEmitter, Input, Output } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { UserService } from '@users/user.service';
import { IconButtonTypes, LoadingService, Toaster } from '@iqser/common-ui';
import { User } from '@red/domain';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { firstValueFrom } from 'rxjs';

@Component({
    selector: 'redaction-reset-password',
    templateUrl: './reset-password.component.html',
})
export class ResetPasswordComponent {
    readonly iconButtonTypes = IconButtonTypes;
    readonly form = this._getForm();
    @Input() user: User;
    @Output() readonly toggleResetPassword = new EventEmitter();

    constructor(
        private readonly _formBuilder: UntypedFormBuilder,
        private readonly _userService: UserService,
        private readonly _loadingService: LoadingService,
        private readonly _toaster: Toaster,
    ) {}

    async save() {
        this._loadingService.start();
        try {
            await firstValueFrom(
                this._userService.resetPassword(
                    {
                        password: this.form.get('temporaryPassword').value,
                        temporary: true,
                    },
                    this.user.id,
                ),
            );
            this.toggleResetPassword.emit();
        } catch (error) {
            this._toaster.error(_('reset-password-dialog.error.password-policy'));
        }
        this._loadingService.stop();
    }

    private _getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            temporaryPassword: [null, Validators.required],
        });
    }
}
