import { Cliente } from './../../auth/interface/cliente';
import { Component } from '@angular/core';
import { Router } from  "@angular/router";
import { Events, MenuController } from '@ionic/angular';
import { AuthService } from '../../auth/service/auth.service';
import { UtilService } from '../../service/util.service';



@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage {
  constructor(private  authService:  AuthService, private  router:  Router, public events: Events, public menuCtrl: MenuController, private utilService: UtilService) {
    this.clienti = [];
    this.clienteSelezionato = {
      denominazione: null,
      id: null
    };
    /*this.authService.isLoggedIn().then(state => {
      if (!state) {
        this.router.navigate(['login']);
      }
    });*/
    this.events.subscribe('functionCall:startup', eventData => {
      if(this.clienteSelezionato.id == null) {
        if(!authService.areClientiSalvati()) 
        {
          setTimeout(() => {
            this.loadClienti()
           }, 3000)
        }
        else this.loadClienti();
      }
    });
   }

  clienti: Cliente[];
  clienteSel;
  clienteSelezionato: Cliente;
  
  async loadClienti()
  {
    this.authService.loadClienti().then(state => {
      this.clienti = AuthService.clienti;
      this.clienteSelezionato = AuthService.clienteSelezionato;
      this.events.publish('functionCall:clienteCambiato', null);
    });
    return true;
  }

  cambiaCliente()
  {
    this.authService.setCliente(this.clienteSel);
    this.clienteSelezionato = AuthService.clienteSelezionato;
    this.events.publish('functionCall:clienteCambiato', null);
  }

  logout(){
    this.authService.logout();
    this.router.navigateByUrl('login');
  }

  ngOnInit() {
  }

  apriPagina(pagina:string)
  {
    this.utilService.apriPagina(pagina);
    this.closeSideMenu();
  }

  

  openSideBar()
  {
    this.menuCtrl.enable(false, 'pareri');
    this.menuCtrl.enable(false, 'topics');
    this.menuCtrl.enable(true, 'mainmenu');
    this.menuCtrl.toggle('mainmenu');
  }

  closeSideMenu() {
    this.menuCtrl.close("mainmenu");
  }
}
