import { HttpClientDataService } from './../../service/http-client-data.service';
import { ParereResponse } from './../../interface/parere-response';
import { ParereModalComponent } from './../../components/parere-modal/parere-modal.component';
import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { UtilService } from '../../service/util.service';
import { RichiesteResponse } from 'src/app/interface/richieste-response';
import { AuthService } from 'src/app/auth/service/auth.service';
import { Richiesta } from 'src/app/interface/richiesta';
import { ParereService } from 'src/app/service/parere.service';
import { ErrorResponse } from '../../auth/interface/error-response';
import { NewRichiestaResponse } from 'src/app/interface/new-richiesta-response';
import { Platform, Events, MenuController } from '@ionic/angular';
import { DataWithFileUploaded } from './../../interface/data-with-file-uploaded';

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

  constructor(
    public menuCtrl: MenuController,
    private utilService:  UtilService, 
    public modalController: ModalController,
    private parereService: ParereService,
    public platform: Platform,
    public events: Events,
    public httpClientDataService: HttpClientDataService,
    ) { 
      this.events.publish('functionCall:startup', null);
      this.initPage();
      if(AuthService.clienteSelezionato.id != null) this.loadPareri("initial");
      this.events.subscribe('functionCall:clienteCambiato', eventData => { 
        this.loadPareri("initial");
      });
    }

  initPage()
  {
    var interventi = new Array();
    this.parereAttivo = {
      idRichiesta: null, 
      nomeFile: null, 
      interventi:interventi,
      titolo: null,
	    testo: null,
	    data: null,
	    url: null,
    	tipo: null
    };
    this.parere = "lista";
    this.bottoneVisibile = true;
    result = {dati: null, file: null};
  }
  
  pareri: Richiesta[];
  parereAttivo: Richiesta;
  idCliente;
  idSelezionato;
  parere: string;
  bottoneVisibile: boolean;

  getFile(id, nomeFile, richiesta)
  {
    var fileUrl = this.httpClientDataService.BASE_ADDRESS+"/intranet/richiesta.do?idcliente="+this.idCliente+"&idrichiesta="+id+"&isrichiesta="+richiesta;
    this.utilService.downloadDocumento(fileUrl, nomeFile);
  }

  async loadPareri(fase)
  {
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    if(fase == "initial") this.parereService.getListaPareri(this.idCliente).subscribe((res: RichiesteResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.pareri = res.richieste;
        if(this.pareri != null && this.pareri.length > 0) this.parereAttivo = this.pareri[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 la procedura di richiesta Topic", ["OK"]);
    });
  }

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

  apriParere(id)
  {
    this.idSelezionato = id;
    this.pareri.forEach(this.setParere, this);
  }

  setParere(parere, index)
  {
    if(parere.idRichiesta == this.idSelezionato)
    { 
      this.parereAttivo = parere;
      this.parere = "dettaglio";
      this.mostraBottone();
      //this.closeSideMenu();
    }
  }

  creaParere(form)
  {
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    this.parereService.newParere(this.idCliente, form.value.title, form.value.question, result.file, form.value.file).subscribe((res: NewRichiestaResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.loadPareri("initial");
        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 creaModale()
  {
    const modal = await this.modalController.create({
      component: ParereModalComponent
    });

    modal.onDidDismiss().then((parere) => {
      if(parere.data != null)
      {
        this.utilService.showLoading();
        this.idCliente = AuthService.clienteSelezionato.id;
        this.parereService.newParere(this.idCliente, parere.data.dati.title, parere.data.dati.question, parere.data.file, parere.data.dati.file).subscribe((res: NewRichiestaResponse)=>{
          this.utilService.closeLoading();
          if(res.error){
            this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
          }
          else 
          {
            this.loadPareri("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 creazione nuovo Topic", ["OK"]);
        });
       /* <input type="file" name="file"  (change)="upload($event)" />

in ts file

upload(str:any)
        const formData = new FormData();

    this.image=str.target.files[0];

    formData.append('files[]', this.image);
    console.log(formData,this.image);
    this.http.post("http://localhost/test/test.php",formData)
    .subscribe((data:any)=>{
      console.log(data);
    })
    console.log(str);*/
      } 
    });

    return await modal.present();
  }

  nascondiBottone()
  {
    this.bottoneVisibile = false;
  }

  mostraBottone()
  {
    this.bottoneVisibile = true;
  }

  async canIAskNewParere(): Promise<boolean>
  {
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    this.parereService.canIAskNewParere(this.idCliente).subscribe((res: ParereResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        if(res.autorizzato)
        {
          //this.creaModale();
          this.parere = "new";
          this.nascondiBottone();
        }
        else{
          this.utilService.presentAlert("Avviso", "", "Hai Superato il numero di pareri per te disponibili. Contattare il tuo referente per poter richiedere nuovi pareri", ["OK"]);
        }
        return res.autorizzato;
      }
    },
    (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 richiesta di limite Pareri superato", ["OK"]);
    });
    return true;
  }

  async createNuovoParere()
  {
    this.canIAskNewParere();
  }

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

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

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

  loadFile()
  {
    var element : HTMLInputElement = document.querySelector('input[type=file]');
    var file: Blob    = element.files[0];
    var reader  = new FileReader();

    reader.onloadend = function () {
      result.file = reader.result;
    };

    /*reader.addEventListener("load", function () {
      result.file = reader.result;
    }, false);*/

    if (file) {
      reader.readAsDataURL(file);
    }
  }

  ngOnInit() {
  }

}

var result: DataWithFileUploaded;
