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

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

  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;

  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.documenti.documenti.forEach(this.toggle, this);
  }

  toggle(documento: Documento, index)
  {
    if(documento.idDocumento == this.idSelected)
    {
      if(documento.checked)  documento.checked = false;
      else{
        documento.checked = true;
        this.showButtons();
      }
    }
    else if(documento.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.documenti.documenti.forEach(this.select, this);
  }

  select(documento: Documento, index)
  {
    if(documento.idDocumento == this.idSelected)
    {
      documento.checked = true;
      this.showButtons();
    }
  }

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

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

  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;
    var idReferente = AuthService.idReferente;
    var strutturaSel = this.utilService.getStrutturaSel();
    if(fase == "initial") request = this.docService.createInitialRequest(idReferente, this.idCliente, strutturaSel.id);
    else request = this.docService.createRequest(idReferente, this.idCliente,null,tit,null,dataDa, dataA, strutturaSel.id);
    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();
      var text = "Errore durante la richiesta di documenti";
      this.utilService.stampaErrore(text, error);
    });
  }

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

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

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

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

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

  ngOnInit() {
  }

}
