import {ActivatedRoute, Router} from "@angular/router";
import {Component} from "@angular/core";
import {
  MessagesService,
  Session,
  UserPasswordResetRequestDto,
  UserService
} from "@webbpm/base-package";
import {BehaviorSubject, Observable} from "rxjs";
import {AsyncPipe, CommonModule} from "@angular/common";
import {FormsModule} from "@angular/forms";

@Component({
             selector: "newPassword",
             templateUrl: "./new_password.html",
             imports: [AsyncPipe, CommonModule, FormsModule]
           })
export class NewPasswordComponent {
  private errorMsgBehavior: BehaviorSubject<string> = new BehaviorSubject<string>(null);

  public currentSession: Observable<Session>;
  public errorMsg: Observable<string>;

  private token: string;

  public password: string;
  public passwordType: boolean;

  public confirmPassword: string;
  public confirmPasswordType: boolean;

  constructor(private router: Router, private userService: UserService,
              private route: ActivatedRoute, private messagesService: MessagesService) {
    this.currentSession = this.userService.getCurrentSession();
    this.errorMsg = this.errorMsgBehavior.asObservable();
  }

  ngOnInit() {
    this.token = this.route.snapshot.queryParamMap.get("token");

    this.router.navigate([], {relativeTo: this.route, replaceUrl: true});

    if (this.token == undefined || this.token === '') {
      this.errorMsgBehavior.next($localize`:|NewPasswordComponent.wrongLinkPleaseRetryMsg:Ссылка недействительна. Требуется повторить восстановление пароля.`);
      return;
    }
  }

  public changePassword(): void {
    let dto: UserPasswordResetRequestDto = new UserPasswordResetRequestDto();
    dto.password = this.password;
    dto.passwordConfirm = this.confirmPassword;
    this.userService.changePassword(dto, this.token)
        .then(() => this.router.navigateByUrl("/"),
              () => {
                this.errorMsgBehavior.next(this.messagesService.getUnknownErrorMessage());
              });
  }

  togglePasswordType(): void {
    this.passwordType = !this.passwordType;
  }

  toggleConfirmPasswordType(): void {
    this.confirmPasswordType = !this.confirmPasswordType;
  }

  isFormValid(): boolean {

    if (this.password === undefined || this.confirmPassword === undefined) {
      return false;
    }
    return this.password === this.confirmPassword;
  }

  onPasswordChange(): void {
    this.updateErrMsg(this.isFormValid())
  }

  private updateErrMsg(valid: boolean) {
    this.errorMsgBehavior.next(
        valid ? null : $localize`:|NewPasswordComponent.passwordMismatchMsg:Введенные пароли не совпадают. Убедитесь, что данные, введенные в поле "Подтверждение пароля", совпадают с теми, которые указаны в поле "Пароль".`);
  }
}
