import { Component, OnInit } from '@angular/core';
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';
import { Events } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';

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

  constructor(private  authService:  AuthService, private  router:  Router, public events: Events, private utilService: UtilService, public translate: TranslateService) {

    this.events.subscribe('functionCall:linguaCambiata', eventData => {
      translate = utilService.translate;
    });
    translate = utilService.translate;

   }

  reset(form){
    this.utilService.showLoading();
    this.authService.reset(form.value).subscribe((res: ErrorResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.errorMsg, ["OK"]);
      }
      else
      {
        this.utilService.presentAlert("Info", "", "Una mail è stata spedita all'indirizzo comunicato con una password temporanea.", ["OK"]);
        this.router.navigateByUrl('/login'); 
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      var text = "Errore durante la procedura di reset password";
      this.utilService.stampaErrore(text, error);
    });
  }

  matching_email_group = new FormGroup({
    
    email: new FormControl('', Validators.compose([
      Validators.required,
      Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
    ]))
  });

  validation_messages = {
    'email': [
        { type: 'required', message: 'Email è richiesta.' },
        { type: 'pattern', message: 'Deve essere composta da numeri e lettere' }
      ]
    }

  ngOnInit() {
  }

  back()
  {
    this.router.navigateByUrl('/login');
  }

}
