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, Events } from '@ionic/angular';
import { Pair } from 'src/app/interface/pair';
import { TranslateService } from '@ngx-translate/core';

@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 events: Events,
    public platform: Platform,
    public translate: TranslateService
    ) 
    {
      this.events.subscribe('functionCall:linguaCambiata', eventData => {
        translate = utilService.translate;
      });
      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;
      this.events.publish('functionCall:linguaCambiata', null);
    }

  linguaSel : string;
  lingue : Array<Pair>;

  cambiaLingua()
  {
    this.utilService.setLingua(this.linguaSel);
    this.utilService.translate.setDefaultLang(this.linguaSel);
    this.utilService.translate.use(this.linguaSel);
    this.events.publish('functionCall:linguaCambiata', null);
  }

  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
        {
          this.utilService.pushNotification(AuthService.idReferente);
          UtilService.titoloPagina = '';
          this.utilService.redirectToFirstPage('notifiche');
          this.events.publish('functionCall:startup', null);
          this.events.publish('functionCall:updateStrutture', null);
        }
      },
        (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() {
  }

}
