import { ErrorResponse } from './../../interface/error-response';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from  "@angular/router";
import { AuthService } from '../../service/auth.service';
import { UtilService } from '../../../service/util.service';
import { Platform } from '@ionic/angular';
import { Pair } from 'src/app/interface/pair';
import { TranslateService } from '@ngx-translate/core';
import { environment } from 'src/environments/environment';
import { EventsService } from 'src/app/service/events.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  encapsulation: ViewEncapsulation.None
})
export class LoginPage implements OnInit {

  constructor(
    private  authService:  AuthService, 
    private  router:  Router, 
    private  utilService:  UtilService, 
    public platform: Platform,
    public translate: TranslateService
    ) 
    {
      this.eventsIdle();
      this.lingue = utilService.getLanguageList();
      if(utilService.getLingua() == "") {
        this.linguaSel = this.lingue[0].key;
        utilService.setLingua(this.linguaSel);
        utilService.translate.setDefaultLang(this.linguaSel);
        utilService.translate.use(this.linguaSel);
      }
      else this.linguaSel = utilService.getLingua();
      translate = utilService.translate;
  }

  eventsIdle()
  {
    this.translate = this.utilService.translate;
    setTimeout(() => {
      this.eventsIdle();
    }, environment.eventsTime);
  }

  linguaSel : string;
  lingue : Array<Pair>;

  cambiaLingua()
  {
    this.utilService.setLingua(this.linguaSel);
    this.utilService.translate.setDefaultLang(this.linguaSel);
    this.utilService.translate.use(this.linguaSel);
  }

  async login(form){
    await this.utilService.showLoading();
      this.authService.login(form.value).subscribe((res: ErrorResponse)=>{
        res = this.authService.errorRespose;
        this.utilService.closeLoading();
        if(res.error){
          this.utilService.presentAlert("Errore", "", res.errorMsg, ["OK"]);
        }
        else
        {
          if(AuthService.idReferente != null) this.utilService.pushNotification(AuthService.idReferente);
          else this.utilService.pushNotification(AuthService.idCliente);
          UtilService.titoloPagina = '';
          this.utilService.redirectToFirstPage('notifiche');
          EventsService.setStartUp();
          EventsService.setUpdateStrutture();
        }
      },
        (error: ErrorResponse) => {
          this.utilService.closeLoading();
          var text = "Errore durante la procedura di login";
          this.utilService.stampaErrore(text, error);
        }
    );
  }

  redirectBusiness()
  {
    this.router.navigate(['businesscall']);
  }

  reset(){
    this.router.navigateByUrl('reset');
  }

  registrazione(){
    this.router.navigateByUrl('registrazione');
  }

  ngOnInit() {
  }

}
