import { Component, OnInit } from '@angular/core';
import { Platform } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { AuthService } from 'src/app/auth/service/auth.service';
import { UtilService } from './../../service/util.service';
import { environment } from '../../../environments/environment';
import { Struttura } from 'src/app/interface/struttura';
import { EventsService } from 'src/app/service/events.service';

@Component({
  selector: 'app-preview-home',
  templateUrl: './preview-home.page.html',
  styleUrls: ['./preview-home.page.scss'],
})
export class PreviewHomePage implements OnInit {

  constructor(
    private  utilService: UtilService,
    public platform: Platform,
    public translate: TranslateService,
    public authService:AuthService
  ) 
  { 
    EventsService.setStartUp();
    this.eventsIdle();
  }

  eventsIdle()
  {
    this.translate = this.utilService.translate;
    setTimeout(() => {
      if(EventsService.clienteCambiato) this.setStrutture();
      if(EventsService.updateStrutture)
      {
        this.setStrutture();
        if(this.startup)
          if(UtilService.redirectToNotifiche)
          {
            UtilService.redirectToNotifiche = false;
            this.utilService.apriPagina("notifiche");
          }
      }
      this.eventsIdle();
    }, environment.eventsTime);
  }

  consultingService: Struttura;
  mediatoreCreditizio: Struttura;
  realEstateBrokerage: Struttura;
  name: String;
  pageReady: boolean = false;
  startup: boolean = true;

  setStrutture()
  {
    this.authService.getId();
    this.authService.getName().then(state => {
      this.name = state;
      this.pageReady = true;
    });;
    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;
    });
  }

  ngOnInit() {
  }

  selectStruttura(struttura:String)
  {
    let ok = false;
    switch(struttura)
    {
      case "servizi":
      {
        this.utilService.setStrutturaSel(this.consultingService);
        ok = true;
        
        this.utilService.setStrutturaName("consulting");
        break;
      }
      case "immobiliare":
      {
        this.utilService.setStrutturaSel(this.realEstateBrokerage);
        ok = true;
        
        this.utilService.setStrutturaName("immobiliare");
        break;
      }
      case "creditizia":
      {
        this.utilService.setStrutturaSel(this.mediatoreCreditizio);
        ok = true;
        
        this.utilService.setStrutturaName("creditizio");
        break;
      }
    }
    EventsService.setStrutturaSelected();
  }

}
