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 { ArchiviaRichiestaResponse } from 'src/app/interface/archivia-richiesta-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';
import { TranslateService } from '@ngx-translate/core';
import { Router } from  "@angular/router";

@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,
    public translate: TranslateService,
    public router: Router
    ) { 
    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");
    });
    this.events.subscribe('functionCall:linguaCambiata', eventData => {
      translate = utilService.translate;
    });
    this.events.subscribe('functionCall:manageBackButton', eventData => {
      if(this.router.url == "/home/parere")
      {
        if(this.parere == "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:parere', null);
            }, 500);
        }
      }
    });
    translate = utilService.translate;
    setTimeout(() => {
      this.refreshPareri();
    }, 60000);
  }

  refreshPareri()
  {
    this.loadPareri('initial');
    setTimeout(() => {
      this.refreshPareri();
    }, 60000);
  }

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

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

  filename: string = "";

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

  toggle(parere: Richiesta, index)
  {
    if(parere.idRichiesta == this.idSelected)
    {
      if(parere.checked)  parere.checked = false;
      else{
        parere.checked = true;
        this.showButtons();
      }
    }
    else if(parere.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.pareri.forEach(this.select, this);
  }

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

  cercaPareri()
  {
    this.loadPareri("initial");
  }

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

  async loadPareri(fase)
  {
    this.hideButtons();
    var titolo = null;
    this.utilService.showLoading();
    this.idCliente = AuthService.clienteSelezionato.id;
    if(this.titolo != null && this.titolo != "") titolo = this.titolo;
    if(fase == "initial") this.parereService.getListaPareri(this.idCliente, this.archiviati, titolo).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();
      var text = "Errore durante la procedura di richiesta Topic";
      this.utilService.stampaErrore(text, error);
    });
  }

  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;
    var filename;
    if(this.platform.is("ios")) filename = this.filename;
    else filename = form.value.file;
    this.parereService.newParere(this.idCliente, form.value.title, form.value.question, result.file, filename).subscribe((res: NewRichiestaResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.archiviati = false;
        this.loadPareri("initial");
        this.apriLista();
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      var text = "Errore durante la procedura di creazione nuovo Topic";
      this.utilService.stampaErrore(text, error);
    });
  }

  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();
          var text = "Errore durante la procedura di creazione nuovo Topic";
          this.utilService.stampaErrore(text, error);
        });
       /* <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();
      var text = "Errore durante la richiesta di limite Pareri superato";
      this.utilService.stampaErrore(text, error);
    });
    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];
    this.filename = element.value;
    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);
    }
  }

  richiestaId;

  checkSelected(id)
  {
    this.clickCheckbox = true;
    this.richiestaId = id;
    this.hideButtons()
    this.pareri.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();
  }

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

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

  pareriSelezionati: Array<number>;
  error: string;

  archiviaPareri(archiviare: boolean)
  {
    this.utilService.showLoading();
    this.pareriSelezionati = new Array();
    this.pareri.forEach(this.raccogliPareri, this);
    this.parereService.archiviaPareri(this.idCliente, archiviare, this.pareriSelezionati).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.loadPareri("initial");
          this.apriLista();
        }
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      var text = "Errore durante l'archiviazione del parere";
      this.utilService.stampaErrore(text, error);
    });
  }

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

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

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

  ngOnInit() {
    
  }

}

var result: DataWithFileUploaded;
