import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MenuController, AlertController, ModalController } from '@ionic/angular';
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';
import { ParereService } from 'src/app/service/parere.service';
import { ArchiviaRichiestaResponse } from 'src/app/interface/archivia-richiesta-response';
import { TranslateService } from '@ngx-translate/core';
import { Router } from  "@angular/router";

@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,
    public parereService: ParereService,
    public translate: TranslateService,
    public router: Router
    ) { 
      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");
      });
      this.events.subscribe('functionCall:linguaCambiata', eventData => {
        translate = utilService.translate;
      });
      translate = utilService.translate;

      this.events.subscribe('functionCall:manageBackButton', eventData => {
        if(this.router.url == "/home/interviste")
        {
          if(this.intervista == "lista")
          {
            
            UtilService.titoloPagina = '';
            this.events.publish('functionCall:cambiaTitolo', null);
            this.router.navigateByUrl('home/index');
          }
          else 
          {
            this.apriLista();
            this.router.navigateByUrl('home/index');
            setTimeout(() => {
              this.events.publish('functionCall:interviste', null);
             }, 500);
          }
        }
      });
      translate = utilService.translate;
      setTimeout(() => {
        this.refreshDomande();
      }, 60000);
  }

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

  refreshDomande()
  {
    this.loadTopics('after');
    setTimeout(() => {
      this.refreshDomande();
    }, 60000);
  }

  resetDate()
  {
    this.date1 = "";
    this.date2 = "";
  }

  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: "",
      archiviato: false
    };
    var date : Date;
    date = new Date();
    this.date1 = "";
    this.date2 = "";
    this.intervista = "lista";
    this.bottoneVisibile = true;
    this.formInserisciIntervento = false;
    this.archiviati = false;
    this.intervisteSelezionate = new Array();
    this.error = "";
    this.titolo = "";
  }

  idSelected: number;
  selection: boolean = false;
  clickCheckbox: boolean = false;

  toggleGroup(id : number)
  {
    if(this.clickCheckbox)
    {
      this.clickCheckbox = false;
      return;
    }
    this.selection = true;
    this.idSelected = id;
    this.hideButtons()
    this.topics.forEach(this.toggle, this);
  }

  toggle(topic: Richiesta, index)
  {
    if(topic.idRichiesta == this.idSelected)
    {
      if(topic.checked)  topic.checked = false;
      else{
        topic.checked = true;
        this.showButtons();
      }
    }
    else if(topic.checked) this.showButtons();
  }

  selectItem(id: number) {
    // alert ("INsiede item selection");
    if(this.clickCheckbox)
    {
      this.clickCheckbox = false;
      return;
    }
    this.selection = true;
    this.idSelected = id;
    this.hideButtons()
    this.topics.forEach(this.select, this);
  }

  select(topic: Richiesta, index)
  {
    if(topic.idRichiesta == this.idSelected)
    {
      topic.checked = true;
      this.showButtons();
    }
  }

  intervisteSelezionate: Array<number>;
  error: string;

  archiviaInterviste(archiviare: boolean)
  {
    this.utilService.showLoading();
    this.intervisteSelezionate = new Array();
    this.topics.forEach(this.raccogliInterviste, this);
    this.parereService.archiviaPareri(this.idCliente, archiviare, this.intervisteSelezionate).subscribe((res: ArchiviaRichiestaResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        if(res.richiesteNonArchiviate.length > 0)
        {
          this.error = "Questa è la lista degli errori:\r\n"
          res.richiesteNonArchiviate.forEach(this.getErrori, this);
          this.utilService.presentAlert("Errore", "", this.error, ["OK"]);
        }
        else{
          this.hideButtons();
          this.loadTopics("after");
          this.apriLista();
        }
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      var text = "Errore durante la procedura di creazione nuovo Topic";
      this.utilService.stampaErrore(text, error);
    });
  }

  showButtons()
  {
    var buttons = document.getElementById('buttonsInterviste');
    buttons.setAttribute("style", "display:block");
  }

  hideButtons()
  {
    var buttons = document.getElementById('buttonsInterviste');
    buttons.setAttribute("style", "display:none");
  }

  richiestaId;

  checkSelected(id)
  {
    this.clickCheckbox = true;
    this.richiestaId = id;
    this.hideButtons()
    this.topics.forEach(this.check, this);
  }

  check(richiesta: Richiesta, index)
  {
    if(richiesta.checked && richiesta.idRichiesta != this.richiestaId) this.showButtons();
    if(!richiesta.checked && richiesta.idRichiesta == this.richiestaId) this.showButtons();
  }

  getErrori(errore: Richiesta, index)
  {
    this.error = "Richiesta n° " + errore.idRichiesta + ":" + errore.errorText;
  }

  raccogliInterviste(richiesta: Richiesta, index)
  {
    if(richiesta.checked) this.intervisteSelezionate.push(richiesta.idRichiesta);
  }

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

  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();
          var text = "Errore durante il caricamento del Topic";
          this.utilService.stampaErrore(text, error);
        });
    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;
    var titolo = null;
    if(this.titolo != null && this.titolo != "") titolo = this.titolo;
    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.hideButtons();
    this.idCliente = AuthService.clienteSelezionato.id;
    this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id, dataDa, dataA, this.archiviati, titolo).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();
      var text = "Errore durante la procedura di apertura del Topic";
      this.utilService.stampaErrore(text, error);
    });
  }

  async loadTopics(fase)
  {
    //this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    if(fase == "initial") this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id, null, null, false, 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();
      var text = "Errore durante la procedura di apertura del Topic";
      this.utilService.stampaErrore(text, error);
    });
    if(fase == "after") this.intervisteService.getListaTopics(AuthService.clienteSelezionato.id, null, null, this.archiviati, 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();
      var text = "Errore durante la richiesta dei Topics";
      this.utilService.stampaErrore(text, error);
    });
  }

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

  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: Richiesta, index)
  {
    if(topic.idRichiesta == this.idSelezionato)
    { 
      this.topicAttivo = topic;
      if(!topic.archiviato) this.mostraBottone();
      else this.nascondiBottone();
      //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();
      var text = "Errore durante la procedura di aggiunta Intervento";
      this.utilService.stampaErrore(text, error);
    });
    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.archiviati = false;
        this.loadTopics("after");
        this.apriLista();
      }
    },
    (error: ErrorResponse) => {
      //this.utilService.closeLoading();
      var text = "Errore durante la procedura di creazione nuovo topic";
      this.utilService.stampaErrore(text, error);
    });
  }

  /*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();
  }*/

  back()
  {
    
    UtilService.titoloPagina = '';
    this.events.publish('functionCall:cambiaTitolo', null);
    this.router.navigateByUrl('home/index');
  }

  ngOnInit() {
  }

}
