import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs';
// import 'rxjs/add/operator/catch';

import { downloadURI } from './background-job-status.component';
//declare var downloadURI : any;
import { map } from "rxjs/operators"; 
// import 'rxjs/Rx';
import { throwError, catchError } from 'rxjs';


@Injectable()
export class BackgroundJobStatusService {
  //private _url:string="/ibase/UploadTemplateServlet?action=GET_UPLOAD_STATUS&BATCH_ID=";GET_UPLOAD_STATUS_Array
    //  
 
  private _url:string="/ibase/UploadStatusServlet?action=GET_BACKGROUNDJOB_STATUS&BATCH_ID=";
  //<!-- added  by sadique shaikh 29-1-2019[to download xls file]  -->
  private downloadFileUrl="/ibase/UploadTemplateServlet?action=DOWNLOAD_FILE&BATCH_ID=";
  //Added By Vikas L. on 3-OCT-2019
  private docHandlerUrl: string = "/ibase/WebITMDocumentHandlerServlet?";
  zipDownlodUrl: any;
  
  constructor(private http:HttpClient) { }
  
  public usUrl="";
  
  
  getBackgroundjobStatus(batchId: any):Observable<any>{

    this.usUrl=this._url+batchId;
    console.log('url path',this.usUrl);
    // return this.http.get<any[]>(this.usUrl).catch(this.errorHandler);
    return this.http.get<any[]>(this.usUrl).pipe(catchError(this.errorHandler));
  }
 //<!-- added  by sadique shaikh 29-1-2019[to download xls file]  -->
  getBackgroundjobDocId(batchId: any):Observable<any>{

    this.usUrl=this.downloadFileUrl+batchId;
    console.log('url path',this.usUrl);
    // return this.http.get(this.usUrl, {responseType : 'text' }).catchError(this.errorHandler);
    return this.http.get(this.usUrl, {responseType : 'text' }).pipe(catchError(this.errorHandler));
  }

  errorHandler(error:HttpErrorResponse)
  {
    // return Observable.throw(error.message || "server Error");
    return throwError(error.message || "server Error");
  }

  /* Added By Vikas Lagad on 3-Oct-2019 [Add method to get encoded URL & download file] Start */
  getEncodedParamString(paramMap: any): any 
  {
    var encodedString = "";
    for (let k in paramMap) 
    {
      var key = k;
      var value = paramMap[k];
      var encod = encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
      encodedString += encod;
    }
    encodedString = encodedString.substring(0, encodedString.length - 1);
    return encodedString;
  }

  downloadZip(paramString: any,fileName: any) 
  {
    this.zipDownlodUrl = this.docHandlerUrl + paramString;
    //var _window = <any>window
    downloadURI(this.zipDownlodUrl,fileName);
  }
  /* Added By Vikas Lagad on 3-Oct-2019 [Add method to get encoded URL & download file] End */
}
