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) {
    this.clienti = [];
    this.clienteSelezionato = {
      denominazione: null,
      id: null
    };
    this.events.subscribe('functionCall:startup', eventData => {
      if(this.clienteSelezionato.id == null) {
        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);
    });
  }

  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)
  {
    switch(pagina)
    {
      case "home":
      {
        this.router.navigateByUrl('home/index');
        this.closeSideMenu();
        break;
      }
      case "documenti":
      {
        this.router.navigateByUrl('home/documenti');
        this.closeSideMenu();
        break;
      }
      case "interviste":
      {
        this.router.navigateByUrl('home/interviste');
        this.closeSideMenu();
        break;
      }
      case "pareri":
      {
        this.router.navigateByUrl('home/parere');
        this.closeSideMenu();
        break;
      }
      case "segreteria":
      {
        this.router.navigateByUrl('home/segreteria');
        this.closeSideMenu();
        break;
      }
      case "change-password":
      {
        this.router.navigateByUrl('home/change-pwd');
        this.closeSideMenu();
        break;
      }
    }
  }

  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");
  }
}
