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 } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { Router } from  "@angular/router";
import { EventsService } from 'src/app/service/events.service';
import { environment } from 'src/environments/environment';
import { TitoliDocumentiResponse } from 'src/app/interface/titolidocumenti-response';

@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,
    private  router:  Router,
    public httpClientDataService: HttpClientDataService,
    public translate: TranslateService
    ) {
    this.documenti = {
      cliente: null,
      error: "",
      documenti: null
    };
    this.date1 = "";
    this.date2 = "";
    this.titolo = "";
    EventsService.setStartUp();
    if(AuthService.clienteSelezionato.id != null) this.chiediDocumenti("initial");
    this.recuperaTitoli();
    this.eventsIdle();
  }

  eventsIdle()
  {
    this.translate = this.utilService.translate;
    if(EventsService.clienteCambiato || EventsService.strutturaSelected || EventsService.strutturaSelectedHome)
    {
      this.chiediDocumenti("initial");
      this.recuperaTitoli();
    }
    setTimeout(() => {
      this.eventsIdle();
    }, environment.eventsTime);
  }

  setDateDa()
  {
    this.datePicker.show({
      date: this.date1 != ""?new Date(this.utilService.dateFormatConvertApp(this.date1)):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: this.date2 != ""?new Date(this.utilService.dateFormatConvertApp(this.date2)):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;
  titoli: string[];

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

  recuperaTitoli()
  {
    var request: DocumentiRequest;
    this.idCliente = AuthService.clienteSelezionato.id;
    var idReferente = AuthService.idReferente;
    var strutturaSel = this.utilService.getStrutturaSel();
    if(strutturaSel == null)
    {
      this.titoli = [];
      return;
    }
    this.utilService.showLoading();
    var usaStruttura: boolean = strutturaSel!=null?strutturaSel.id != 6:true;
    request = this.docService.createTitoloRequest(idReferente, this.idCliente,strutturaSel.id, usaStruttura);
    this.docService.getTitoli(request).subscribe((res: TitoliDocumentiResponse)=>{
      this.utilService.closeLoading();
      if(res.error){
        this.utilService.presentAlert("Errore", "", res.error, ["OK"]);
      }
      else 
      {
        this.titoli = res.titoli;
      }
    },
    (error: ErrorResponse) => {
      this.utilService.closeLoading();
      var text = "Errore durante la richiesta di documenti";
      this.utilService.stampaErrore(text, error);
    });
  }

  chiediDocumenti(fase)
  {
    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();
    var usaStruttura: boolean = strutturaSel!=null?strutturaSel.id != 6:true;
    if(strutturaSel == null)
    {
      this.documenti = {
        cliente: null,
        error: "",
        documenti: []
      };
      return;
    }
    this.utilService.showLoading();
    if(fase == "initial") request = this.docService.createInitialRequest(idReferente, this.idCliente, strutturaSel.id, usaStruttura);
    else request = this.docService.createRequest(idReferente, this.idCliente,null,tit,null,dataDa, dataA, strutturaSel.id, usaStruttura);
    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.router.navigateByUrl('home/index');
  }

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

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

  ngOnInit() {
  }

}
