import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn, Validators} from "@angular/forms";
import {FormHelperService} from "../../services/form-helper.service";
import {AuthenticationService} from "../../services/authentication.service";
import {ToastrService} from "ngx-toastr";

@Component({
  selector: 'app-password-change',
  templateUrl: './password-change.component.html',
  styleUrls: ['./password-change.component.scss']
})
export class PasswordChangeComponent implements OnInit {

  public  passwordChangeForm: FormGroup ;
  public  loading: boolean = false;

  constructor(
    public validationService: FormHelperService,
    public authenticationService: AuthenticationService,
    private toastr: ToastrService
    ) { }

  ngOnInit(): void {
    this.passwordChangeForm = new FormGroup({
        passwordOld: new FormControl(null, [ Validators.required, ]),
        password: new FormControl(null, [ Validators.required,Validators.minLength(6)]),
        passwordRepeat: new FormControl(null, [ Validators.required,Validators.minLength(6)]),
      },
      {
        validators: [this.checkPasswords]
      });
  }

  changePassword() {
    if (!this.passwordChangeForm.valid){
      return;
    }
    this.loading = true;
    this.authenticationService.passwordChange({
      passwordOld: this.passwordChangeForm.value.passwordOld,
      password: this.passwordChangeForm.value.password
    }).subscribe(value => {
        this.loading = false;
        this.toastr.success('Sikeresen megváltoztatta a jelszavát', 'Jelszó módosítás');
        this.passwordChangeForm.reset();
    },
      error => {
        this.loading = false;
        this.toastr.error(error, 'Jelszó módosítás');
      })
  }

  checkPasswords: ValidatorFn = (group: AbstractControl):  ValidationErrors | null => {


    if ( group.hasError("password") || group.hasError("passwordRepeat")){
      return null;
    }
    if ( !group.get("passwordRepeat").dirty ||  !group.get("passwordRepeat").touched ){
      return null;
    }

    let password = this.validationService.getValue(this.passwordChangeForm,"password");
    let passwordRepeat = this.validationService.getValue(this.passwordChangeForm,"passwordRepeat");

    return password === passwordRepeat ? null : { notSame: true }
  }

}
