import { Component, OnInit } from '@angular/core';
import { PasswordValidator } from '../../validators/password.validator';
import { Validators, FormControl, FormGroup } from '@angular/forms';
import { Router } from  "@angular/router";
import { AuthService } from '../../service/auth.service';
import { ErrorResponse } from '../../interface/error-response';
import { UtilService } from '../../../service/util.service';

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

  constructor(private  authService:  AuthService, private  router:  Router, private  utilService:  UtilService) { }

  change(form){
    this.utilService.showLoading();
    this.authService.getId().then(state => {
      this.authService.changePwd(form.value).subscribe((res: ErrorResponse)=>{
        this.utilService.closeLoading();
        if(res.error){
          this.utilService.presentAlert("Errore", "", res.errorMsg, ["OK"]);
        }
        else 
        {
          this.utilService.presentAlert("Info", "", "La Password è stata cambiata correttamente", ["OK"]);
          this.router.navigateByUrl('');
        }
      },
      (error: ErrorResponse) => {
        this.utilService.closeLoading();
        if(error != null && error.errorMsg != null) this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
        else if(error!=null) this.utilService.presentAlert("Errore", "", error, ["OK"]);
        else this.utilService.presentAlert("Errore", "", "Errore durante la procedura di cambio password", ["OK"]);
      });
    });
  }

matching_passwords_group = new FormGroup({
    
    oldpassword: new FormControl('', Validators.required),
    newpassword: new FormControl('', Validators.compose([
      Validators.minLength(5),
      Validators.required,
      Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$') //this is for the letters (both uppercase and lowercase) and numbers validation
    ])),
    newpasswordbis: new FormControl('', Validators.compose([
      Validators.required
    ]))
  },(formGroup: FormGroup) => {
    return PasswordValidator.areEqual(formGroup);
  });

  validation_messages = {
    'newpassword': [
        { type: 'required', message: 'Password è richiesta.' },
        { type: 'minlength', message: 'La lunghezza minima è 5 caratteri' },
        { type: 'pattern', message: 'Deve essere composta da numeri e lettere' }
      ],
    'newpasswordbis': [
        { type: 'areEqual', message: 'La password deve essere uguale a quella nuova' },
        { type: 'required', message: 'Il Repeat Password è richiesto.' }
      ]
    }

  ngOnInit() {
  }

}
