import { Injectable } from '@angular/core';
import { NewRichiestaRequest } from '../interface/new-richiesta-request';
import { NewRichiestaResponse } from '../interface/new-richiesta-response';
import { Observable, of} from  'rxjs';
import { RichiesteResponse } from '../interface/richieste-response';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpClientDataService } from '../service/http-client-data.service';
import { tap, catchError } from  'rxjs/operators';
import { RichiesteRequest } from '../interface/richieste-request';
import { Pair } from './../interface/pair';

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

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

  errorRespose;

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

  getTopic(idCliente, idRichiesta, dataDa, dataA): Observable<RichiesteResponse>
  {
    var richiesta = this.creaGetListaRichiesta(idCliente, idRichiesta, null, dataDa, dataA);
    var param = this.encodeBody(richiesta);
    return this.httpClient.post<RichiesteResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/topic.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;          
        }
      })
    );
  }

  getListaTopics(idCliente: number, dataDa, dataA): Observable<RichiesteResponse>
  {
    var limite = null;
    if(dataDa == null && dataA == null) limite = 10;
    var richiesta = this.creaGetListaRichiesta(idCliente, null, limite, dataDa, dataA);
    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;          
        }
      })
    );
  }

  creaGetListaRichiesta(id, idRichiesta, limite, dataDa, dataA): 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);
    }
    pair = {
      key: "tipo",
      value: "DOMANDA",
      type: "string"
    }
    pairs.push(pair);

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

    return request;
  }

  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")
        request += "\""+filtro.key + "\":"+filtro.value;
      else
        request += "\""+filtro.key + "\":\""+filtro.value+"\"";
    }
    request += "}}";
    return request;
  }

  newTopic(id, title, question)
  {

    var richiesta = this.creaRichiestaNuova(id, title, question);
    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;          
        }
      })
    );

  }

  addIntervento(idCliente, message, idTopic)
  {

    var richiesta = this.creaIntervento(idCliente, message, idTopic);
    var param = this.encodeNuovoIntervento(richiesta);
    return this.httpClient.post<NewRichiestaResponse>(this.httpClientDataService.BASE_ADDRESS+'/intranet/newintervento.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;          
        }
      })
    );
    return null;

  }

  creaIntervento(id, message, idTopic): NewRichiestaRequest
  {
    var request:NewRichiestaRequest;
    request = {
      cliente: id,
      richiesta: idTopic,
      titolo: null,
      testo: message,
      tipo: "DOMANDA",
      file: null,
      nomeFile: null
    };

    return request;
  }

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

    return request;
  }

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

  encodeNuovaRichiesta(params: NewRichiestaRequest) {
    var request = "{\"cliente\" : "+params.cliente+",\"richiesta\" : "+params.richiesta+",\"titolo\" : \""+params.titolo+"\",\"testo\" : \""+params.testo+"\",\"tipo\" : \""+params.tipo+"\",\"file\" : "+params.file+",\"nomeFile\" : \""+params.nomeFile+"\"}";
    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);
  };
}
