import { Cliente } from './../../auth/interface/cliente';
import { Component } from '@angular/core';
import { Router } from  "@angular/router";
import { Events, MenuController, Platform } from '@ionic/angular';
import { AuthService } from '../../auth/service/auth.service';
import { UtilService } from '../../service/util.service';
import { Pair } from 'src/app/interface/pair';
import { TranslateService } from '@ngx-translate/core';
import { SegreteriaService } from './../../service/segreteria.service';
import { StruttureResponse } from './../../interface/strutture-response';
import { ErrorResponse } from '../../auth/interface/error-response';
import { environment } from '../../../environments/environment';
import { Struttura } from 'src/app/interface/struttura';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage {
  constructor(
    private  authService:  AuthService,
    private segreteriaService: SegreteriaService,
    private  router:  Router, 
    public events: Events, 
    public menuCtrl: MenuController, 
    private utilService: UtilService, 
    public translate: TranslateService,
    public platform: Platform
    ) {
    this.clienti = [];
    this.titoloPagina = "";
    this.clienteSelezionato = {
      denominazione: null,
      id: null
    };
    this.tipoStruttura = environment.struttura;
    /*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();
      }
    });
    this.events.subscribe('functionCall:linguaCambiata', eventData => {
      translate = utilService.translate;
    });
    this.events.subscribe('functionCall:parere', eventData => {
      this.router.navigateByUrl('home/parere');
    });
    this.events.subscribe('functionCall:interviste', eventData => {
      this.router.navigateByUrl('home/interviste');
    });
    this.events.subscribe('functionCall:strutturaSelected', eventData => {
      this.strutturaSelected();
    });
    this.events.subscribe('functionCall:cambiaTitolo', eventData => {
      this.titoloPagina = UtilService.titoloPagina;
    });
    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.platform.backButton.subscribeWithPriority(0, () => {
      let defaultUrl: string []=[
        "/home",
        "/login",
        "/reset",
        "/businesscall",
        "/privacy",
        "/home/index",
        "/home/documenti",
        "/home/change-pwd",
        "/home/segreteria"
      ];

      if(defaultUrl.indexOf(this.router.url) != -1)
      {
        switch(this.router.url)
        {
          case "/login":
          {
            navigator['app'].exitApp();
            break;
          }
          case "/home":
          case "/home/index":
          case "/reset":
          case "/businesscall":
          case "/home/preview-home":
          {
            this.router.navigateByUrl('login');
            break;
          }
          case "/privacy":
          {
            this.router.navigateByUrl('businesscall');
            break;
          }
          case "/home/documenti":
          case "/home/change-pwd":
          case "/home/segreteria":
          {
            this.router.navigateByUrl('home/index');
            break;
          }
        }
      }
      else this.events.publish('functionCall:manageBackButton', null);
    });
   }

   isTitolo()
   {
     return this.titoloPagina != '';
   }

   loadStrutture()
   {
     //this.utilService.showLoading();
     this.segreteriaService.getStrutture(AuthService.clienteSelezionato.id, this.tipoStruttura).subscribe((res: StruttureResponse)=>{
       //this.utilService.closeLoading();
       UtilService.strutture = res.strutture;
       this.events.publish('functionCall:updateStrutture', null);
       this.setStrutture();
       if(!UtilService.strutture.includes(this.utilService.getStrutturaSel()))
        this.router.navigateByUrl('home/preview-home');
     },
     (error: ErrorResponse) => {
       //this.utilService.closeLoading();
       var text = "Errore durante la richiesta lista strutture";
       this.utilService.stampaErrore(text, error);
     });
   }

  clienti: Cliente[];
  clienteSel;
  clienteSelezionato: Cliente;
  linguaSel: string;
  lingue : Array<Pair>;
  tipoStruttura: string;
  showMenuButton: boolean = false;
  consultingService: Struttura;
  mediatoreCreditizio: Struttura;
  realEstateBrokerage: Struttura;
  idStrutturaSel: number;
  titoloPagina: string;

  selectStruttura(struttura:String)
  {
    let ok = false;
    switch(struttura)
    {
      case "servizi":
      {
        if(this.consultingService != null)
        {
          this.utilService.setStrutturaSel(this.consultingService);
          ok = true;
        }
        break;
      }
      case "immobiliare":
      {
        if(this.realEstateBrokerage != null)
        {
          this.utilService.setStrutturaSel(this.realEstateBrokerage);
          ok = true;
        }
        break;
      }
      case "creditizia":
      {
        if(this.mediatoreCreditizio != null)
        {
          this.utilService.setStrutturaSel(this.mediatoreCreditizio);
          ok = true;
        }
        break;
      }
    }
    if(ok)
    {
      this.strutturaSelected();
      this.events.publish('functionCall:strutturaSelectedHome', null);
    }
    else{
      this.utilService.stampaAvviso("Struttura non presente in questo profilo");
    }
  }

  strutturaSelected()
  {
    var struttutaSel = this.utilService.getStrutturaSel();
    this.idStrutturaSel = struttutaSel.id;
    this.showMenuButton = true;
    if(!this.platform.is("desktop")) this.closeSideMenu();
    this.router.navigateByUrl('home/index');
  }

  gotoPreview()
  {
    this.router.navigateByUrl('home/preview-home');
  }

  setStrutture()
  {
    this.utilService.getStruttura(environment.ConsultingServiceId).then(struttura => 
    {
      this.consultingService = struttura;
    });
    this.utilService.getStruttura(environment.MediatoreCreditizioId).then(struttura => 
    {
      this.mediatoreCreditizio = struttura;
    });
    this.utilService.getStruttura(environment.RealEstateBrokerageId).then(struttura => 
    {
      this.realEstateBrokerage = struttura;
    });
  }
  
  async loadClienti()
  {
    this.authService.loadClienti().then(state => {
      this.clienti = AuthService.clienti;
      this.clienteSelezionato = AuthService.clienteSelezionato;
      this.events.publish('functionCall:clienteCambiato', null);
      this.loadStrutture();
    });
    return true;
  }

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

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

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

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