import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// import 'rxjs/add/observable/from';
// import { Observable } from 'rxjs/Observable';
import { Observable, BehaviorSubject, from } from 'rxjs';
import { map } from "rxjs/operators"; 
 // import 'rxjs/Rx';

@Injectable()
export class SearchComponent {
  private _url: string = "/ibase/WEBITMRIARequestHandlerServlet?";
  private _urlZip: string = "/ibase/resource/HeaderDataZIPFiles/"
  private _urlPophelpFields = "/ibase/RIAWizardHandlerServlet?";
   //Added By Vikas L. on 3-OCT-2019 [To get the background job data]
  private _urlUploadStatus = "/ibase/UploadStatusServlet?";

  isPermntFilter!: boolean;

  colInfoNodeListMap = {};
  editselectedInputFieldIndx!: number;//to remove index from filterValuePromtTxtBoxArr 
  isCheckBoxStatusArr: any[] = [];
  public Url = "";
  public viewDataUrl = "";
  public downloadFileUrl = "";
  public pophelpFieldUrl = "";
  public uploadStatusUrl ="";
  downloadZipUrl = "";

  private displayNameMapRev = {};//Checked
  private displayNameMap = {};//Checked
  private fieldTypeMap:any = {};//Checkd
  private physicalNameMap:any = {};//Checked
  private operatorNameMap:any = {};//Checked
  private opratorMapkeys!: string[];
  private fieldDispNameMapkeys!: string[];
  filterValuePromtTxtBoxArr:any = [];
  //new bydefaultfilte -start
  prmntFilterValuePromtTxtBoxArr:any = [];//Stores propm input values
  isPrmntCheckBoxStatusArr:any = [];//stores check box record in true/false format
  prmntValuePmptArrLst :any= [];//strires prompt/value record
  prmntFilterValueArrLst :any= [];//Store harcoded filter values from input
  prmntOperatorNameArrLst :any= [];//Dtores the operator like =,>,< etc.
  prmntFieldNameArrLst:any = [];//Stores Field names 
  prmntOperandNameArrList:any = []; //Stores operand like and/or
  permntFilterNamesArrLstForMap:any = [];//Stores filter names without split for expression map
  prmntFilterNamesArrLstLabel:any = [];//Stores filter names with split
  //new bydefaultfilte -end
  pophelpData:any;
  //Default for sun
  dateFormat = 'dd/MM/yy';
  //Added by Sainath T. on 28-03-2020-Start
  applDateFormatFromJsp: string = '';
  constructor(private http: HttpClient) { }

  getObjDetailResponse(paramString:any): Observable<any> {
    this.Url = this._url + paramString;
    //console.log('url path', this.Url);
    return this.http.get(this.Url, { responseType: 'text' }); //need to define what type of data is coming
  }

  getViewData(paramString:any): Observable<any> {
    this.viewDataUrl = this._url + paramString;
    //console.log('Url 2 Path>>', this.viewDataUrl);
    return this.http.get(this.viewDataUrl, { responseType: 'text' });
  }

  getPopHelpFields(paramString:any): Observable<any> {
    this.pophelpFieldUrl = this._urlPophelpFields + paramString;
    //console.log('Url 4 Path>>', this.pophelpFieldUrl);
    return this.http.get(this.pophelpFieldUrl, { responseType: 'text' });
  }

  getPophelpData(dataSource: string, filterName: string, isRefresh: boolean, inputData: string): Observable<any> {
    console.log("in get pophelp data service!!");
    let headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    let options = { headers: headers };
    var loginId = localStorage.getItem('userName');
    //console.log("getPophelpData filterName", loginId, filterName);
    if (loginId) {
      filterName = loginId + '_' + filterName + '_' + inputData;
    }
    //console.log("getPophelpData filterName", filterName);

    if (!isRefresh) {
      this.pophelpData = localStorage.getItem(filterName);
      if (this.pophelpData) {
        //console.log("Data found data in local storage");
        var dataHandler = new BehaviorSubject<any>(JSON.parse(this.pophelpData));
        // return dataHandler;
        // return Observable.from(dataHandler)
        return from(dataHandler)
      }
    }
    // return this.http.get<any>(this.getHostURL() + dataSource, options)
    //   .map((res:any) => this.extractData(res, filterName));
    return this.http.get<any>(this.getHostURL() + dataSource, options)
      .pipe(map((res:any) => this.extractData(res, filterName)));
  }

  private extractData(res: Response, filterName:any) {
    console.log('extractData[' + JSON.stringify(res) + ']');
    let body = res.json();
    localStorage.setItem(filterName, JSON.stringify(body));

    return body || {};
  }

  //To get encoded URL
  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);
    //console.log("the encodedString :" + encodedString);
    return encodedString;
  }

  downlopadFile(filename: string): Observable<any> {
    this.downloadFileUrl = this._urlZip + filename;
    //console.log('url path', this.downloadFileUrl);
    return this.http.get(this.downloadFileUrl, { responseType: 'arraybuffer' });
  }

  setColInFoNodeListMap(objName: any, colInfoNodeList: HTMLCollectionOf<Element> | NodeListOf<Element>): any {
    this.setOperatorFieldNameMap(colInfoNodeList);
  }

  /**
   * This method set operator & field name in hashmap
   * @param colInfoNodeLst
   */
  setOperatorFieldNameMap(colInfoNodeLst: HTMLCollectionOf<Element> | NodeListOf<Element>) {
    console.log('In setOperatorFieldNameMap:::');
    var physicalNameMap:any = {};
    var fieldTypeMap:any = {};
    var displayNameMap:any = {};
    var displayNameMapRev:any = {};
    var operatorNameMap:any = {};
    var opratorMapkeys: string[];
    var fieldDispNameMapkeys: string[];
    for (var i = 0; i < colInfoNodeLst.length; i++) {
      var colinfo:any = colInfoNodeLst.item(i) as Element;
      //console.log('colinfo', colinfo);
      var displayName = colinfo.attributes.getNamedItem("displayName").nodeValue;
      //console.log('displayName', displayName);

      var logicalName = colinfo.attributes.getNamedItem("logicalName").nodeValue;
      //console.log('logicalName', logicalName);

      var phyName = colinfo.attributes.getNamedItem("physicalName").nodeValue;
      //console.log('phyName', phyName);

      var type = colinfo.attributes.getNamedItem("type").nodeValue;
      //console.log('type', type);

      var computeString = colinfo.attributes.getNamedItem("computeString").nodeValue;
      //console.log('computeString', computeString);

      physicalNameMap[logicalName] = phyName;
      fieldTypeMap[logicalName] = type;

      if (phyName.indexOf(".") != -1) {
        displayNameMap[logicalName] = displayName;
        displayNameMapRev[displayName] = logicalName;
      }
      operatorNameMap[" "] = " ";

      operatorNameMap["="] = "=";

      operatorNameMap[">"] = ">";

      operatorNameMap["<"] = "<";

      operatorNameMap[">="] = ">=";

      operatorNameMap["<="] = "<=";

      operatorNameMap["!="] = "!=";

      operatorNameMap["LIKE ENDS WITH"] = "LIKE ENDS WITH";
      operatorNameMap["LIKE STARTS WITH"] = "LIKE STARTS WITH";
      operatorNameMap["CONTAINS"] = "CONTAINS";
      operatorNameMap["IN"] = "IN";
      operatorNameMap["BETWEEN"] = "BETWEEN";

      console.log('At the end!!!!!!!!!!!!!');
    }
    opratorMapkeys = Object.keys(operatorNameMap);
    fieldDispNameMapkeys = Object.keys(displayNameMap);
    this.setdisplayNameMapRev(displayNameMapRev);
    this.setdisplayNameMap(displayNameMap);
    this.setfieldTypeMap(fieldTypeMap);
    this.setphysicalNameMap(physicalNameMap);
    this.setoperatorNameMap(operatorNameMap);
    this.setopratorMapkeys(opratorMapkeys);
    this.setfieldDispNameMapkeys(fieldDispNameMapkeys);
    //console.log('opratorMapkeys!!!!!>', this.opratorMapkeys, 'fieldDispNameMapkeys>>', this.fieldDispNameMapkeys, 'this.displayNameMap>>', this.displayNameMap);
  }

  public getdisplayNameMapRev() {
    return this.displayNameMapRev;
  }
  public setdisplayNameMapRev(value:any) {
    this.displayNameMapRev = value;
  }
  public getdisplayNameMap() {
    return this.displayNameMap;
  }
  public setdisplayNameMap(value:any) {
    this.displayNameMap = value;
  }
  public getfieldTypeMap() {
    return this.fieldTypeMap;
  }
  public setfieldTypeMap(value:any) {
    this.fieldTypeMap = value;
  }
  public setphysicalNameMap(value:any) {
    this.physicalNameMap = value;
  }
  public getphysicalNameMap(fieldName:any) {
    return this.physicalNameMap[fieldName];
  }
  public getoperatorNameMap() {
    return this.operatorNameMap;
  }
  public setoperatorNameMap(value:any) {
    this.operatorNameMap = value;
  }
  public getopratorMapkeys(): string[] {
    return this.opratorMapkeys;
  }
  public setopratorMapkeys(value: string[]) {
    this.opratorMapkeys = value;
  }
  public getfieldDispNameMapkeys(): string[] {
    return this.fieldDispNameMapkeys;
  }
  public setfieldDispNameMapkeys(value: string[]) {
    this.fieldDispNameMapkeys = value;
  }
  //From Add filter
  setFilterValuePromtTxtBoxArr(filterValuePromtTxtBox: any, indx: number): any {
    this.filterValuePromtTxtBoxArr[indx] = filterValuePromtTxtBox;
    //console.log('this.filterValuePromtTxtBoxArr>> after set', this.filterValuePromtTxtBoxArr);
  }
  getFilterValuePromtTxtBoxArr(): any {
    return this.filterValuePromtTxtBoxArr;
  }

  //New-prmntbydefault-start
  setPrmntFilterValuePromtTxtBoxArr(filterValuePromtTxtBox: any, indx: number): any {
    this.prmntFilterValuePromtTxtBoxArr[indx] = filterValuePromtTxtBox;
    //console.log('this.prmntFilterValuePromtTxtBoxArr>> after set', this.prmntFilterValuePromtTxtBoxArr);
  }
  getPrmntFilterValuePromtTxtBoxArr(): any {
    return this.prmntFilterValuePromtTxtBoxArr;
  }
  //New-prmntBydefault -end

  removeselectedFilterValuePromtTxtBoxArrIndex(editSelectedInputFieldIndx: number): any {
    this.filterValuePromtTxtBoxArr.splice(editSelectedInputFieldIndx, 1);
    //console.log('this.filterValuePromtTxtBoxArr after delete', this.filterValuePromtTxtBoxArr);
  }

  //By default filter - start
  setPrmntCheckBoxStatus(isChecked: boolean, a: any): any {
    this.isPrmntCheckBoxStatusArr[a] = isChecked;
    //console.log('this.isPrmntCheckBoxStatusArr>> after set', this.isPrmntCheckBoxStatusArr);
  }
  getPrmntCheckBoxStatus() {
    return this.isPrmntCheckBoxStatusArr;
  }

  setprmntfilterNamesArrLst(filterNamesArrLstLabel: any[], index: number) {
    this.prmntFilterNamesArrLstLabel[index] = filterNamesArrLstLabel;
  }
  getprmntfilterNamesArrLst() {
    return this.prmntFilterNamesArrLstLabel;
  }
  setPermanentFltrNameListForMap(permntFilterNamesArrLst: any[]) {
    this.permntFilterNamesArrLstForMap = permntFilterNamesArrLst;
  }
  getPermanentFltrNameListForMap() {
    return this.permntFilterNamesArrLstForMap;
  }
  setPrmntOperandNameArrList(operandIndxArrList: any[], index: number) {
    this.prmntOperandNameArrList[index] = operandIndxArrList;
  }
  getPrmntOperandNameArrList() {
    return this.prmntOperandNameArrList;
  }
  setPrmntfieldNameArrLst(fieldNameArrLst: any[], index: number) {
    this.prmntFieldNameArrLst[index] = fieldNameArrLst;
  }
  getPrmntfieldNameArrLst() {
    return this.prmntFieldNameArrLst;
  }
  setPrmntoperatorNameArrLst(operatorNameArrLst: any[], index: number) {
    this.prmntOperatorNameArrLst[index] = operatorNameArrLst;
  }
  getPrmntoperatorNameArrLst() {
    return this.prmntOperatorNameArrLst;
  }
  setPrmntfilterValueArrLst(filterValueArrLst: any[], index: number) {
    this.prmntFilterValueArrLst[index] = filterValueArrLst;
  }
  getPrmntfilterValueArrLst() {
    return this.prmntFilterValueArrLst;
  }

  setPrmntValuePmptArrLst(valuePmptIndxArrLst: any[], index: number) {
    this.prmntValuePmptArrLst[index] = valuePmptIndxArrLst;
  }
  getPrmntValuePmptArrLst() {
    return this.prmntValuePmptArrLst;
  }

  //By default filter - end
  //To check object is empty even it is jsonArray  or JSONObject
  isEmpty(obj:any) {
    try {
      if (obj == null) return true;
      if (obj.length > 0) return false;
      if (obj.length === 0) return true;
      if (typeof obj !== "object") return true;
      for (var key in obj) {
        if (SearchComponent.hasOwnProperty.call(obj, key)) return false;
      }
    }
    catch{
      console.log('Error while checking json is empty');
    }
    //Refer Link:https://stackoverflow.com/questions/4994201/is-object-empty
    return true;
  }

  getHostURL(): string {
    let HOST_URL: string = '';
    HOST_URL = localStorage.getItem('HOST_URL');
    // HOST_URL = JSON.parse(localStorage.getItem('HOST_URL')||"{}");
    if (!HOST_URL) {
      HOST_URL = '';
    }
    console.log('getHostURL[', HOST_URL, ']');
    return HOST_URL;
  }

  //error related
  getErrorData(viewDataResponse: any): any {
    var errorArr:any = [];
    var errorDom:any = new Document();
    var parser = new DOMParser();
    errorDom = parser.parseFromString(viewDataResponse, "text/xml");
    console.log('getErrorData xmlDoc>>1', errorDom.lastElementChild.lastChild);
    try {
      var msg = errorDom.getElementsByTagName("message")[0].childNodes[0].nodeValue;
      errorArr[0] = msg;
    }
    catch{
      console.log('error while getting errorMsg');
      errorArr[0] = "";
    }
    try {
      var trace = errorDom.getElementsByTagName("trace")[0].childNodes[0].nodeValue;
      errorArr[1] = trace;
    }
    catch{
      console.log('error while getting errorTrace');
      errorArr[0] = "";
    }
    try {
      var descr = errorDom.getElementsByTagName("description")[0].childNodes[0].nodeValue;
      errorArr[2] = descr;
    }
    catch{
      console.log('error while getting errorDescr');
      errorArr[0] = "";
    }
    return errorArr;
  }

  getErrorMsg(msg:any, msgDescr:any, msgTrace:any) {
    console.log(' in getErrorMsg');
    var response = "";
    response = msg + "\n" + msgTrace + "\n" + msgDescr;
    return response;
  }
  //error related -end

  //For Date Format
  getDateFormat() {
    var dateFormatFrmLocal = localStorage.getItem('APPL_DATE_FORMAT');
    console.log('dateFormatFrmLocal[', dateFormatFrmLocal, '] applDateFormatFromJsp['+this.applDateFormatFromJsp+']');
    //Added by Sainath T. on 28-03-2020-Start
    if(this.applDateFormatFromJsp.trim().length > 0)
    {
      this.dateFormat = this.applDateFormatFromJsp;
    }
    //Added by Sainath T. on 28-03-2020-Start
    else if (dateFormatFrmLocal && dateFormatFrmLocal.length > 0) 
    {
      this.dateFormat = dateFormatFrmLocal;
    }
    console.log('dateFormat[', this.dateFormat, ']');
    return this.dateFormat;
  }

  //To get date object
  getDateObj(inputDate:any) {
    console.log('In getDateObj>',inputDate);
    if(inputDate == undefined || inputDate == 'undefined')
    {
      return "";
    }
    var dateString = inputDate;
    var dateParts: any = dateString.split("/");
    // month is 0-based, that's why we need dataParts[1] - 1
    var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
    console.log('dateObject400[',dateObject,']');
    return dateObject;
  }

  setLoading(flag : boolean)
  {
    try
    {
      (<any>window.parent).setLoading(flag);
    }
    catch{
      console.log('window.setLoading is not a function!!');        
    }
  }
   
  /* Added By Vikas Lagad on 3-Oct-2019 [Add method for get upload Status detail & download file] Start */
  uploadStatus(paramString:any): Observable<any> 
  {
    this.uploadStatusUrl = this._urlUploadStatus + paramString;
    return this.http.get(this.uploadStatusUrl, { responseType: 'text' });
  }

  downloadZip(paramString:any) : Observable<any>
  {
    this.downloadZipUrl = this.downloadZipUrl + paramString;
    return this.http.get(this.downloadZipUrl, { responseType: 'text' });
  }
  /* Added By Vikas Lagad on 3-Oct-2019 [Add method for get upload Status detail & download file] End */
  //Added by Sainath T. on 28-03-2020-Start
  setApplDateFormatFromJsp(applDateFormatFromJsp: string) 
  {
    this.applDateFormatFromJsp = applDateFormatFromJsp;
  }
  //Added by Sainath T. on 28-03-2020-End

}
