import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MenuController, AlertController, ModalController } from '@ionic/angular';
import {ModalQuestionComponent} from '../../components/modal-question/modal-question.component';
import {OverlayEventDetail} from '@ionic/core';
import { UtilService } from '../../service/util.service';
import { Richiesta } from 'src/app/interface/richiesta';
import { AuthService } from 'src/app/auth/service/auth.service';
import { RichiesteResponse } from 'src/app/interface/richieste-response';
import { ErrorResponse } from '../../auth/interface/error-response';
import {IntervisteService} from '../../service/interviste.service';
import { NewRichiestaResponse } from 'src/app/interface/new-richiesta-response';
import { DatePicker } from '@ionic-native/date-picker/ngx';
import { Platform, Events } from '@ionic/angular';

@Component({ 
  selector: 'app-interviste',
  templateUrl: './interviste.page.html',
  styleUrls: ['./interviste.page.scss']
})

export class IntervistePage implements OnInit {

  constructor(
    public menuCtrl: MenuController, 
    public alertCtrl: AlertController, 
    public modalController: ModalController, 
    private authService: AuthService,
    private  utilService:  UtilService,
    private datePicker: DatePicker,
    private intervisteService: IntervisteService, 
    public platform: Platform,
    public events: Events
    ) { 
      this.events.publish('functionCall:startup', null);
      this.initPage();
      if(AuthService.clienteSelezionato.id != null) this.loadTopics("initial");
      this.events.subscribe('functionCall:clienteCambiato', eventData => { 
        this.loadTopics("initial");
      });
  }

  topicAttivo: Richiesta;
  topics;
  idSelezionato;
  idCliente;
  date1;
  date2;
  message;
  intervista;
  bottoneVisibile: boolean;
  formInserisciIntervento: boolean;

  initPage()
  {
    var interventi = new Array();
    this.topicAttivo = {
      idRichiesta: null, 
      nomeFile: null, 
      interventi:interventi,
      titolo: null,
	    testo: null,
	    data: null,
	    url: null,
      tipo: null,
      checked: false,
      errorText: ""
    };
    var date : Date;
    date = new Date();
    this.date1 = "";
    this.date2 = "";
    this.intervista = "lista";
    this.bottoneVisibile = true;
    this.formInserisciIntervento = false;
  }

  apriLista()
  {
    this.intervista = "lista";
    this.mostraBottone();
  }

  nascondiBottone()
  {
    this.bottoneVisibile = false;
    this.hideInputIntervento();
  }

  mostraBottone()
  {
    this.bottoneVisibile = true;
  }

  showInputIntervento()
  {
    var footer = document.getElementById('footer-interviste');
    footer.setAttribute("style", "height:150px");
    this.formInserisciIntervento = true;
  }

  hideInputIntervento()
  {
    var footer = document.getElementById('footer-interviste');
    footer.setAttribute("style", "height:90px");
    this.formInserisciIntervento = false;
  }

  caricaTopic()
  {
    var dataA = null;
    var dataDa = null;
    if(this.date1 != null  && this.date1 != "") dataDa = this.utilService.dateFormatConvert(this.date1);
    if(this.date2 != null  && this.date2 != "") dataA = this.utilService.dateFormatConvert(this.date2);
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    this.intervisteService.getTopic(AuthService.clienteSelezionato.id, this.topicAttivo.idRichiesta, dataDa, dataA).subscribe((res: RichiesteResponse)=>{
      this.utilService.closeLoading();
          if(res.error){
            this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
          }
          else 
          {
            this.topicAttivo = res.richieste[0];
          }
        },
        (error: ErrorResponse) => {
          this.utilService.closeLoading();
          if(error != null && error.errorMsg != null) this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
          else if(error!=null) this.utilService.presentAlert("Errore", "", error, ["OK"]);
          else this.utilService.presentAlert("Errore", "", "Errore durante il caricamento del Topic", ["OK"]);
        });
    return true; 
  }

  setDateDa()
  {
    this.datePicker.show({
      date: new Date(),
      mode: 'date',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
    }).then(
      date => this.date1 = this.utilService.getAndroidDateString(date),
      err => console.log('Error occurred while getting date: ', err)
    );
  }

  setDateA()
  {
    this.datePicker.show({
      date: new Date(),
      mode: 'date',
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
    }).then(
      date => this.date2 = this.utilService.getAndroidDateString(date),
      err => console.log('Error occurred while getting date: ', err)
    );
  }

  caricaRichieste()
  {
    var dataA = null;
    var dataDa = null;
    if(this.date1 != null && this.date1 != "") dataDa = this.utilService.dateFormatConvert(this.date1);
    if(this.date2 != null  && this.date1 != "") dataA = this.utilService.dateFormatConvert(this.date2);
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id, dataDa, dataA).subscribe((res: RichiesteResponse)=>{ 
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.topics = res.richieste;
        /*if(this.topics != null && this.topics.length > 0 && this.topicAttivo.idRichiesta == null) this.topicAttivo = this.topics[0];
        else this.apriTopic(this.topicAttivo.idRichiesta);*/
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      if(error != null && error.errorMsg != null) this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
        else if(error!=null) this.utilService.presentAlert("Errore", "", error, ["OK"]);
        else this.utilService.presentAlert("Errore", "", "Errore durante la procedura di apertura del Topic", ["OK"]);
    });
  }

  async loadTopics(fase)
  {
    //this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    if(fase == "initial") this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id, null, null).subscribe((res: RichiesteResponse)=>{ 
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.topics = res.richieste;
        if(this.topics != null && this.topics.length > 0 && this.topicAttivo.idRichiesta == null) this.topicAttivo = this.topics[0];
        else this.apriTopic(this.topicAttivo.idRichiesta);
      }
      //this.utilService.closeLoading();
    },
    (error: ErrorResponse) => {
      //this.utilService.closeLoading();
      if(error != null && error.errorMsg != null) this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
        else if(error!=null) this.utilService.presentAlert("Errore", "", error, ["OK"]);
        else this.utilService.presentAlert("Errore", "", "Errore durante la procedura di apertura del Topic", ["OK"]);
    });
    if(fase == "after") this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id, null, null).subscribe((res: RichiesteResponse)=>{ 
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.topics = res.richieste;        
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
    });
  }

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

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

  async createNewTopics()
  {
    const alert = await this.alertCtrl.create({
    header: 'New Topic',
    inputs: [
      {
        name: 'title',
        placeholder: 'Nome del Topic',
        type: 'text'
      },
      {
        name: 'question',
        placeholder: 'Inserisci domanda',
        type: 'text'
      },
    ],
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        handler: data => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'Salva',
        handler: data => {
          this.saveNewTopic(data); 
        }
      }
    ]
    });
    
    alert.present();
  }

  trackByDoc(index: number, topic: Richiesta): number { return topic.idRichiesta; }

  apriTopic(id)
  {
    this.idSelezionato = id;
    this.topics.forEach(this.setTopic, this);
    this.intervista = "dettaglio";
    this.mostraBottone();
  }

  apriEdit()
  {
    if(this.intervista == "dettaglio")
    {
      if(this.formInserisciIntervento) this.hideInputIntervento();
      else this.showInputIntervento();
    }
    if(this.intervista == "lista")
    {
      this.nascondiBottone();
      this.hideInputIntervento();
      this.intervista = "new";
    }
  }

  setTopic(topic, index)
  {
    if(topic.idRichiesta == this.idSelezionato)
    { 
      this.topicAttivo = topic;
      //this.closeSideMenu();
    }
  }

  aggiungiIntervento(form)
  {
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    var element : HTMLInputElement = document.querySelector('input[type=text]');
    var message = element.value;
    this.intervisteService.addIntervento(this.idCliente, message, this.topicAttivo.idRichiesta).subscribe((res: NewRichiestaResponse)=>{
      this.utilService.closeLoading();
      this.message = "";
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.loadTopics("initial");
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      if(error != null && error.errorMsg != null) this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
      else if(error!=null) this.utilService.presentAlert("Errore", "", error, ["OK"]);
      else this.utilService.presentAlert("Errore", "", "Errore durante la procedura di aggiunta Intervento", ["OK"]);
    });
    return true;
  }

  saveNewTopic(form)
  {
    //this.utilService.showLoading();
      this.idCliente = AuthService.clienteSelezionato.id;
      this.intervisteService.newTopic(this.idCliente, form.value.title, form.value.question).subscribe((res: NewRichiestaResponse)=>{
        //this.utilService.closeLoading();
        if(res.error){
          this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
        }
        else 
        {
          this.loadTopics("after");
          this.apriLista();
        }
      },
      (error: ErrorResponse) => {
        //this.utilService.closeLoading();
        if(error != null && error.errorMsg != null) this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
        else if(error!=null) this.utilService.presentAlert("Errore", "", error, ["OK"]);
        else this.utilService.presentAlert("Errore", "", "Errore durante la procedura di creazione nuovo topic", ["OK"]);
      });
  }

  /*async createModal() {
      const modal = await this.modalController.create({
        component: ModalQuestionComponent, 
        componentProps: { value: 123 }
      });

      modal.onDidDismiss().then((question: OverlayEventDetail) => {
        if(question.data == null) this.utilService.presentAlert("Fatto", "", "E' stato cliccato cancel", ["OK"]);
        else this.utilService.presentAlert("Fatto", "", question.data, ["OK"]);
      });

      return await modal.present();
  }

  async createNewQuestion()
  {
    var result = await this.createModal();
  }*/

  ngOnInit() {
  }

}
