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';

@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
    };
  }
  
  pareri: Richiesta[];
  parereAttivo: Richiesta;
  idCliente;
  idSelezionato;

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

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

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

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

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

  ngOnInit() {
  }

}
