import { ArchiviaRichiestaRequest } from '../interface/archivia-richiesta-request';
import { ParereResponse } from './../interface/parere-response';
import { Injectable } from '@angular/core';
import { UtilService } from '../service/util.service';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpClientDataService } from '../service/http-client-data.service';
import { RichiesteResponse } from '../interface/richieste-response';
import { ArchiviaRichiestaResponse } from 'src/app/interface/archivia-richiesta-response';
import { Observable, of} from  'rxjs';
import { RichiesteRequest } from '../interface/richieste-request';
import { Pair } from './../interface/pair';
import { tap, catchError } from  'rxjs/operators';
import { ErrorResponse } from '../auth/interface/error-response';
import { NewRichiestaRequest } from '../interface/new-richiesta-request';
import { NewRichiestaResponse } from '../interface/new-richiesta-response';

@Injectable({
  providedIn: 'root'
})
export class ParereService {

  constructor(
    private  httpClient: HttpClient,
    private  httpClientDataService: HttpClientDataService) {
      this.initService();

  }

  initService()
  {
    this.errorRespose = { 
      error: true,
      errorMsg: ""
    };
  }

  creaRichiesta(id, limite, dataDa, dataA, archiviati): RichiesteRequest
  {
    var request:RichiesteRequest;
    var pair:Pair;
    var pairs: Pair[] = new Array();
    if(dataDa != null)
    {
      pair = {
        key: "daData",
        value: dataDa,
        type: "string"
      }
      pairs.push(pair);
    }

    if(dataA != null)
    {
      pair = {
        key: "aData",
        value: dataA,
        type: "string"
      }
      pairs.push(pair);
    }

    if(archiviati != null)
    {
      pair = {
        key: "archiviato",
        value: archiviati,
        type: "boolean"
      }
      pairs.push(pair);
    }

    pair = {
      key: "tipo",
      value: "PARERE",
      type: "string"
    }
    pairs.push(pair);

    request = {
      cliente: id,
      limite: limite,
      richiesta: null,
      filtri: pairs
    };

    return request;
  }

  creaRichiestaNuova(id, title, question, file, nomeFile): NewRichiestaRequest
  {
    var request:NewRichiestaRequest;
    if(!file) file = null;
    request = {
      cliente: id,
      richiesta: null,
      titolo: title,
      testo: question,
      tipo: "PARERE",
      file: file,
      nomeFile: nomeFile
    };

    return request;
  }

  creaRichiestaArchiviazione(id, archiviare, pareriSelezionati): ArchiviaRichiestaRequest
  {
    var request: ArchiviaRichiestaRequest;
    request = {
      cliente: id,
      daArchiviare: archiviare,
      listaRichieste: pareriSelezionati
    };

    return request;
  }

  archiviaPareri(id, archiviare, pareriSelezionati)
  {
    var richiesta = this.creaRichiestaArchiviazione(id, archiviare, pareriSelezionati);
    var param = this.encodeArchiviaRichiesta(richiesta);
    return this.httpClient.post<ArchiviaRichiestaResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/setrichiestedaarchiviare.do', param, this.httpClientDataService.httpOptionsJson)
      .pipe(
      catchError(this.handleError),
      tap( (res: ArchiviaRichiestaResponse ) => {

        if (!res.error) {
          this.errorRespose.error = false;
          return res;
        }
        else{
          this.errorRespose.error = true;
          this.errorRespose.errorMsg = res.error;          
        }
      })
    );
  }

  newParere(id, title, question, file:string, nomeFile:string)
  {

    if(nomeFile.indexOf('/') != -1) nomeFile = nomeFile.substring(nomeFile.lastIndexOf('/')+1);
    else if(nomeFile.indexOf('\\') != -1) nomeFile = nomeFile.substring(nomeFile.lastIndexOf('\\')+1);
    if(file != null) file = file.substring(file.lastIndexOf('base64,')+7)
    var richiesta = this.creaRichiestaNuova(id, title, question, file, nomeFile);
    var param = this.encodeNuovaRichiesta(richiesta);
    return this.httpClient.post<NewRichiestaResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/newrichiesta.do', param, this.httpClientDataService.httpOptionsJson)
      .pipe(
      catchError(this.handleError),
      tap( (res: NewRichiestaResponse ) => {

        if (!res.error) {
          this.errorRespose.error = false;
          return res;
        }
        else{
          this.errorRespose.error = true;
          this.errorRespose.errorMsg = res.error;          
        }
      })
    );

  }

  canIAskNewParere(idCliente: string)
  {
    var param = UtilService.encodeBody({idcliente: idCliente});
    return this.httpClient.post<ParereResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/checkparere.do', param, this.httpClientDataService.httpOptions)
    .pipe(
      catchError(this.handleError),
      tap( (res:  ParereResponse ) => {

        if (!res.error) {
          this.errorRespose.error = false;
          return res;
        }
        else{
          this.errorRespose.error = true;
          this.errorRespose.errorMsg = res.error;          
        }
      })
    );
  }

  getListaPareri(idCliente: string, archiviati: boolean): Observable<RichiesteResponse>
  {
    var richiesta = this.creaRichiesta(idCliente, 10, null, null, archiviati);
    var param = this.encodeBody(richiesta);
    return this.httpClient.post<RichiesteResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/richieste.do', param, this.httpClientDataService.httpOptionsJson)
      .pipe(
      catchError(this.handleError),
      tap( (res:  RichiesteResponse ) => {

        if (!res.error) {
          this.errorRespose.error = false;
          return res;
        }
        else{
          this.errorRespose.error = true;
          this.errorRespose.errorMsg = res.error;          
        }
      })
    );
  }

  errorRespose: ErrorResponse; 

  handleError(error: HttpErrorResponse) {
    this.errorRespose = { 
      error: true,
      errorMsg: ""
    };
    if (error.error instanceof ErrorEvent) {
      this.errorRespose.errorMsg = error.error.message;
    } else {
      this.errorRespose.errorMsg = error.error;
    }
    return of(this.errorRespose);
  };

  encodeBody(params: RichiesteRequest) {
    var request = "{\"cliente\" : "+params.cliente+",\"limite\" : "+params.limite+",\"richiesta\" : "+params.richiesta+",\"filtri\" : {";
    var filtro;
    var first = true;
    var i;
    for (i = 0; i < params.filtri.length; i++) {
      filtro = params.filtri[i];
      if(first) first = false;
      else request += ", ";
      if(filtro.type == "int" || filtro.type == "boolean")
        request += "\""+filtro.key + "\":"+filtro.value;
      else
        request += "\""+filtro.key + "\":\""+filtro.value+"\"";
    }
    request += "}}";
    return request;
  }

  encodeNuovaRichiesta(params: NewRichiestaRequest) {
    var request;
    if(params.file == null) request = "{\"cliente\" : "+params.cliente+",\"richiesta\" : "+params.richiesta+",\"titolo\" : \""+params.titolo+"\",\"testo\" : \""+params.testo+"\",\"tipo\" : \""+params.tipo+"\",\"file\" : "+params.file+",\"nomeFile\" : \""+params.nomeFile+"\"}";
    else request = "{\"cliente\" : "+params.cliente+",\"richiesta\" : "+params.richiesta+",\"titolo\" : \""+params.titolo+"\",\"testo\" : \""+params.testo+"\",\"tipo\" : \""+params.tipo+"\",\"file\" : \""+params.file+"\",\"nomeFile\" : \""+params.nomeFile+"\"}";
    return request;
  }

  encodeArchiviaRichiesta(params: ArchiviaRichiestaRequest)
  {
    var request ="{\"cliente\" : " + params.cliente + ", \"daArchiviare\" : " + params.daArchiviare + ", \"listaRichieste\" : [";
    var first = true;
    for(let richiesta of params.listaRichieste)
    {
      if(first) 
      {
        first = false;
        request += "\""+richiesta+"\"";
      }
      else request += ", \""+richiesta+"\"";
    }
    request += "]}";
    return request;
  }
}
