import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { UtilService } from 'src/app/service/util.service';
import { Platform } from '@ionic/angular';
import { Router } from '@angular/router';
import { AuthService } from '../../service/auth.service';
import { ErrorResponse } from '../../interface/error-response';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { EventsService } from 'src/app/service/events.service';
import { AppVersion } from '@ionic-native/app-version/ngx';

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

  constructor(
    private  authService:  AuthService,
    private  router:  Router,
    public platform: Platform,
    private utilService: UtilService,
    public translate: TranslateService,
    public appVersion: AppVersion
  ) {
    this.eventsIdle();
    this.setAppData();
    translate = utilService.translate;
   }

   appName;
   versionNumber;

   async setAppData()
   {
    if(!this.platform.is("desktop"))
    {
      this.appName = await this.appVersion.getAppName();
      this.versionNumber = await this.appVersion.getVersionNumber();
    }
   }

   eventsIdle()
   {
     setTimeout(() => {
       this.translate = this.utilService.translate;
       this.eventsIdle();
    }, EventsService.timeoutEvents);
   }

  ngOnInit() {
  }

  registra(form){
    this.utilService.showLoading();
    this.authService.registra(form.value).subscribe((res: ErrorResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.errorMsg, ["OK"]);
      }
      else
      {
        this.utilService.presentAlert("Info", "", "Registrazione effettuata con successo", ["OK"]);
        if(AuthService.idReferente != null) this.utilService.pushNotification(AuthService.idReferente);
        else this.utilService.pushNotification(AuthService.idCliente);
        UtilService.titoloPagina = '';
        this.utilService.redirectToFirstPage('notifiche');
        setTimeout(() => {
          EventsService.setStartUp();
          EventsService.setUpdateStrutture();
        }, 1000);
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      var text = "Errore durante la procedura di registrazione";
      this.utilService.stampaErrore(text, error);
    });
  }

  matching_email_group = new FormGroup({

    nome: new FormControl('', Validators.compose([
      Validators.required,
    ])),
    cognome: new FormControl('', Validators.compose([
      Validators.required,
    ])),
    email: new FormControl('', Validators.compose([
      Validators.required,
      Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
    ])),
    cellulare: new FormControl('', Validators.compose([
      Validators.required,
    ])),
    password: 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
    ])),
    passwordbis: new FormControl('', Validators.compose([
      Validators.required
    ]))
  });

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

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

}
