import { StruttureResponse } from './../interface/strutture-response';
import { FattureResponse } from './../interface/fatture-response';
import { Pair } from './../interface/pair';
import { P2pResponse } from './../interface/p2p-response';
import { FattureRequest } from './../interface/fatture-request';
import { Injectable } from '@angular/core';
import { tap, catchError } from  'rxjs/operators';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpClientDataService } from '../service/http-client-data.service';
import { ErrorResponse } from '../auth/interface/error-response';
import { UtilService } from './util.service';
import { of } from 'rxjs/observable/of';


@Injectable({
  providedIn: 'root'
})

export class SegreteriaService {

  constructor(
    private  httpClient: HttpClient,
    public httpClientDataService: HttpClientDataService
  ) {
    this.errorRespose = { 
      error: true,
      errorMsg: ""
    };
  }

  errorRespose: ErrorResponse;

  createFatturaRequest(id, limite, daData, aData, nProgNotula, nNotula, struttura)
  {
    var request: FattureRequest;
    var pair:Pair;
    var pairs: Pair[] = new Array();
    if(daData != null)
    {
      pair = {
        key: "daData",
        value: daData,
        type: "string"
      }
      pairs.push(pair);
    }

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

    if(nProgNotula != null)
    {
      pair = {
        key: "numeroProgetto",
        value: nProgNotula,
        type: "int"
      }
      pairs.push(pair);
    }

    if(nNotula != null)
    {
      pair = {
        key: "numeroNotula",
        value: nNotula,
        type: "int"
      }
      pairs.push(pair);
    }

    request = {
      cliente: id,
      limite: limite,
      struttura: struttura,
      filtri: pairs
    };
    return request;
  }

  getP2pToken(idCliente)
  {
    //idCliente = 1096;
    var body = UtilService.encodeBody({userkey: idCliente});
    return this.httpClient.post<P2pResponse>(this.httpClientDataService.P2PTokenUrl, body, this.httpClientDataService.httpOptions)
      .pipe(
      catchError(this.handleError),
      tap( (res: P2pResponse ) => {

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

  }

  getFatture(request)
  {
    var param = this.encodeBody(request);
    return this.httpClient.post<FattureResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/notule.do', param, this.httpClientDataService.httpOptionsJson)
      .pipe(
      catchError(this.handleError),
      tap( (res:  FattureResponse ) => {

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

  getStrutture(idUser, tipoStruttura)
  {
    var param = UtilService.encodeBody({idcliente: idUser, tipostruttura: tipoStruttura});
    return this.httpClient.post<StruttureResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/strutture.do', param, this.httpClientDataService.httpOptions)
      .pipe(
      catchError(this.handleError),
      tap( (res:  StruttureResponse) => { 

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

  getStruttureByReferente(idUser, tipoStruttura)
  {
    var param = UtilService.encodeBody({idreferente: idUser, tipostruttura: tipoStruttura});
    return this.httpClient.post<StruttureResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/struttureByReferente.do', param, this.httpClientDataService.httpOptions)
      .pipe(
      catchError(this.handleError),
      tap( (res:  StruttureResponse) => { 

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

  encodeBody(params)
  {
    var request = "{\"cliente\" : "+params.cliente+",\"limite\" : "+params.limite+",\"struttura\" : "+params.struttura+",\"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")
        request += "\""+filtro.key + "\":"+filtro.value;
      else
        request += "\""+filtro.key + "\":\""+filtro.value+"\"";
    }
    request += "}}";
    return request;
  }

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