import { Pair } from './../../interface/pair';
import { HttpClientDataService } from './../../service/http-client-data.service';
import { Documento } from './../../interface/documento';
import { UtilService } from './../../service/util.service';
import { DocumentiResponse } from './../../interface/documenti-response';
import { Component, OnInit } from '@angular/core';
import { DocumentiService } from 'src/app/service/documenti.service';
import { AuthService } from 'src/app/auth/service/auth.service';
import { ErrorResponse } from '../../auth/interface/error-response';
import { DocumentiRequest } from '../../interface/documenti-request';
import { DatePicker } from '@ionic-native/date-picker/ngx';
import { Platform, Events } from '@ionic/angular';

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

  

  constructor(
    private  docService: DocumentiService,
    private  utilService: UtilService,
    private datePicker: DatePicker, 
    public platform: Platform,
    public events: Events,
    public httpClientDataService: HttpClientDataService
    ) {
    this.documenti = {
      cliente: null,
      error: "",
      documenti: null
    };
    this.date1 = "";
    this.date2 = "";
    this.titolo = "";
    this.events.publish('functionCall:startup', null);
    if(AuthService.clienteSelezionato.id != null) this.chiediDocumenti("initial");
    this.events.subscribe('functionCall:clienteCambiato', eventData => { 
      this.chiediDocumenti("initial");
    });
  }

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

  idCliente;

  getDocumento(idDoc, nomeFile: string)
  {
    var fileUrl = this.httpClientDataService.BASE_ADDRESS+"/intranet/documento.do?idcliente="+this.idCliente+"&iddocumento="+idDoc;
    //this.utilService.downloadDocumento(fileUrl, nomeFile);
    this.utilService.shareDocumento(fileUrl, nomeFile);
  }

  documentoId;

  checkSelected(id)
  {
    this.documentoId = id;
    this.hideButtons()
    this.documenti.documenti.forEach(this.check, this);
  }

  check(documento: Documento, index)
  {
    if(documento.checked && documento.idDocumento != this.documentoId) this.showButtons();
    if(!documento.checked && documento.idDocumento == this.documentoId) this.showButtons();
  }

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

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

  docSel: Array<Pair>;

  async condividiDocumenti()
  {
    this.docSel = new Array();
    this.documenti.documenti.forEach(this.recuperaDocumento, this);
    this.utilService.shareDocumenti(this.docSel);
  }

  async recuperaDocumento(documento: Documento, index)
  {
    if(documento.checked != null && documento.checked) 
    {
      var coppia: Pair;
      coppia = {
        key: documento.nomeFile,
        value: documento.url,
        type: "string"
      }
      this.docSel.push(coppia);
    }
    //this.utilService.shareDocumento(documento.url, documento.nomeFile);
  }

  chiediDocumenti(fase)
  {
    this.utilService.showLoading();
    var dataA = null;
    var dataDa = null;
    var tit = null;
    if(this.titolo != "") tit = this.titolo;
    if(this.date1 != null  && this.date1 != "") dataDa = this.utilService.dateFormatConvert(this.date1);
    if(this.date2 != null  && this.date2 != "") dataA = this.utilService.dateFormatConvert(this.date2);
    var request: DocumentiRequest;
    this.idCliente = AuthService.clienteSelezionato.id;
    if(fase == "initial") request = this.docService.createInitialRequest(this.idCliente);
    else request = this.docService.createRequest(this.idCliente,null,tit,null,dataDa, dataA);
    this.docService.getDocumenti(request).subscribe((res: DocumentiResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.documenti = res;
        this.documenti.documenti.forEach(this.editTitle, this);
      }
    },
    (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 dei documenti", ["OK"]);
    });
  }

  editTitle(documento: Documento, index)
  {
    if(documento.titolo.indexOf("/") > 0) documento.titolo = documento.titolo.substring(0, documento.titolo.length - 11);
  }

  cercaDocumenti()
  {
    this.chiediDocumenti("ricerca");
  }

  trackByDoc(index: number, doc: Documento): number { return doc.idDocumento; }

  documenti: DocumentiResponse;
  date1;
  date2;
  titolo: string;

  ngOnInit() {
  }

}
