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;

  initPage()
  {
    var interventi = new Array();
    this.topicAttivo = {
      idRichiesta: null, 
      nomeFile: null, 
      interventi:interventi,
      titolo: null,
	    testo: null,
	    data: null,
	    url: null,
    	tipo: null
    };
    var date : Date;
    date = new Date();
    this.date1 = this.utilService.getDateString(date);
    this.date2 = this.utilService.getDateString(date);
  }

  caricaTopic()
  {
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    this.intervisteService.getTopic(AuthService.clienteSelezionato.id, this.topicAttivo.idRichiesta, this.utilService.dateFormatConvert(this.date1), this.utilService.dateFormatConvert(this.date2)).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();
          this.utilService.presentAlert("Errore", "", error.errorMsg, ["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.getDateString(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.getDateString(date),
      err => console.log('Error occurred while getting date: ', err)
    );
  }

  async loadTopics(fase)
  {
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    if(fase == "initial") this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id).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();
      this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
    });
    if(fase == "after") this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id).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);
  }

  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();
      this.utilService.presentAlert("Errore", "", error.errorMsg, ["OK"]);
    });
    return true;
  }

  saveNewTopic(data)
  {
    this.utilService.showLoading();
      this.idCliente = AuthService.clienteSelezionato.id;
      this.intervisteService.newTopic(this.idCliente, data.title, data.question).subscribe((res: NewRichiestaResponse)=>{
        this.utilService.closeLoading();
        if(res.error){
          this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
        }
        else 
        {
          this.loadTopics("initial");
        }
      },
      (error: ErrorResponse) => {
        this.utilService.closeLoading();
        this.utilService.presentAlert("Errore", "", error.errorMsg, ["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() {
  }

}
