import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { NanoValidators } from 'src/app/shared/nano-validators';
import { DialogService } from 'src/app/shared/services/dialog.service';
import { NanoDialogBase } from 'src/app/shared/dialogs/nano-base-dialog';

@Component({
  selector: 'app-change-password-dialog',
  templateUrl: './change-password-dialog.component.html',
  styleUrls: ['./change-password-dialog.component.scss']
})
export class ChangePasswordDialogComponent extends NanoDialogBase<ChangePasswordDialogComponent> implements OnInit {
  strength: number = 0;

  passwordForm = new FormGroup({
    password: new FormControl('', [Validators.required]),
    passwordAgain: new FormControl('', [Validators.required])
  });

  constructor(public dialogRef: MatDialogRef<ChangePasswordDialogComponent>, private dialogService: DialogService) { 
    super(dialogRef);
  }

  ngOnInit(): void {
    this.passwordForm.get("passwordAgain").addValidators([NanoValidators.controlEquals(this.passwordForm.get("password"))]);
    this.passwordForm.get("password").addValidators([NanoValidators.passwordStrengthLow(() => this.strength)]);

    this.passwordForm.get("password").valueChanges.subscribe(e => {
      if(this.passwordForm.get("passwordAgain").touched){
        this.passwordForm.get("passwordAgain").updateValueAndValidity();
      }
    });
  }

  public passwordStrength(score) {
    this.strength = score;
    this.passwordForm.get("password").updateValueAndValidity();
  }

  changePassword(){
    this.dialogRef.close(this.passwordForm.get('password').value);
  }
}
