import { Component, OnInit } from '@angular/core';
import { Platform, Events } 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';

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

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

  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":
      {
        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.events.publish('functionCall:strutturaSelected', null);
    else{
      this.utilService.stampaAvviso("Struttura non presente in questo profilo");
    }
  }

}
