import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { SearchComponent } from '../searchComponent.service';
import { HomePagePopuppanelComponent } from '../home-page-popuppanel/home-page-popuppanel.component'
import { empty } from 'rxjs';
import { AppDateAdapter, APP_DATE_FORMATS } from '../date.adapter';
import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'custom-filter',
  templateUrl: './custom-filter.component.html',
  styleUrls: ['./custom-filter.component.css'],
  providers: [
    {
      provide: DateAdapter, useClass: AppDateAdapter
    },
    {
      provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
    },
    DatePipe
  ]
})
export class CustomFilterComponent implements OnInit {

  @Input('isCustomFilter') isCustomFilter: boolean = false;
  @Input('editFilterJson') editFilterJson: any;
  @Input('objName') objName: any;
  @ViewChild(HomePagePopuppanelComponent) homePagePopUpComp!: HomePagePopuppanelComponent;
  @Output() onClose: EventEmitter<any> = new EventEmitter();
  @Output() onDone: EventEmitter<any> = new EventEmitter();
  @Output() onRemove: EventEmitter<any> = new EventEmitter();

  //For getting drop down values -Start
  andOrValueO:any = [];
  promptValueO:any = [];
  operatorValueO:any = [];
  fileldValueO:any = [];
  //For getting drop down values -End
  isClick = false; //checked
  codtnValueArr = [""]; // checked Stores and or details
  promtValuOptArr:any = []; // checked Stores prompt/value details
  operatorNameArrLst:any = []; // Checked Stores Operator names like +,-,>,<=
  fieldNameArrLst:any = [];//Checked Strore selected Field Names
  isAdded = 1; // To Set the andOrArray to iterate the ngFor 
  andOrAddArr = ["1"] //its andOrArray to iterate the ngFor
  promptSelField = [false];// To set inputField for value when not prompt selected, it should be flase
  promCount = 0; // Not Used yet
  isDateArr = [false]; // Cheched when field data type is true create date field
  filterNamesArrLst:any = []; //Checked 
  filterValueArrLst:any = [];//Checked to store input values when selected "Value"
  filterName = "";//Checkd
  //Sai for dynamic dropdown list values
  public displayNameMap = {};//Checked
  private fieldTypeMap:any = {};//Checkd
  //private physicalNameMap = {};//Checked
  private operatorNameMap:any = {};//Checked
  opratorMapkeys!: string[];
  operatrValue: any[] = [];//changed to string to array
  fieldDispNameMapkeys!: string[];
  optnValue: string = "Value"; //Value/Prompt
  valuePromptListArr = ["Value", "Prompt"];
  listBoxOperand = ["", "And", "Or"];
  codtnOprandValue: string = "";

  displayNameMapRev = {}; // for getting logical name by display name
  isDoneEmitFlag: boolean = false; // will be true whenever all fields are filled.n will emit the ondone

  //For Edit filter-Start
  editFilterValueArrLst:any = [];
  editFieldNameSelectedArr: any[] = [] //To set default selected fields on edit;
  editOpratorNameSelectedArr: any[] = [];
  editPromtValueSelectedArr: any[] = [];
  isEditJson: boolean = true;
  editCodtnValueSelectedArr: any[] = [];
  filtertextValue:any = [];//for getting entered i/p data on click of value option
  editselectedInputFieldIndx: any = null; //to get selecte input field index on edit to remove from add filter array.
  editselectedFilterName: string = "";//to get selected filter name to remove from allexprmap
  //For Edit filter-End
  //For BETWEEN -START
  filterBtwntextValueFrm:any = [];//For getting entered i/p data in Between operator fields on click of value opti
  filterBtwntextValueTo:any = [];
  filterBtwntextValueArr:any = [];
  //For BETWEEN -End
  isRemoveBtnVisible: boolean = false;//Flag for on edit remove button visible
  filterNameArrForExprMap:any = [];//Stores filter names without splited for allexpressionMap
  isValueCheckBoxStatusArr:any = [];//It stores the check box status true or false
  // andOrAddArrFlag: boolean = false;
  indexArrayForPushAndOrAddArr: any[] = [null];//Dummy for and or counter increment
  dateFormat = '';
  constructor(private _searchMenuService: SearchComponent, public datePipe: DatePipe) { }

  ngOnInit() {
    console.log('::::In CustomFilterComponent:::::objName', this.objName);
    this.dateFormat = this._searchMenuService.getDateFormat();    //To get APPL_DATE_FORMAT

    this.displayNameMapRev = this._searchMenuService.getdisplayNameMapRev();
    this.displayNameMap = this._searchMenuService.getdisplayNameMap();
    this.fieldTypeMap = this._searchMenuService.getfieldTypeMap();
    this.operatorNameMap = this._searchMenuService.getoperatorNameMap();
    this.opratorMapkeys = this._searchMenuService.getopratorMapkeys();
    this.fieldDispNameMapkeys = this._searchMenuService.getfieldDispNameMapkeys();
    //For edit filter data -START
    //console.log('in custom filter editFilterJson ngOnChanges>>', this.editFilterJson);
    this.isEditJson = this._searchMenuService.isEmpty(this.editFilterJson);//if false then only json is not null
    if (!this.isEditJson) {
      console.log('in edit Json');

      var editFilterNamesArrLst = this.editFilterJson['filterNamesArrLst'];
      var editFilterValueArrLst = this.editFilterJson['filterValueArrLst'];
      this.seteditFilterValueArrLst(editFilterValueArrLst);

      var editisValueCheckBoxStatusArr = this.editFilterJson['isValueCheckBoxStatusArr'];
      //console.log('editisValueCheckBoxStatusArr[', editisValueCheckBoxStatusArr, ']');

      var editFieldNameArrLst = this.editFilterJson['fieldNameArrLst'];
      var editPromtValuOptArr = this.editFilterJson['promtValuOptArr'];
      var editCodtnValueArr = this.editFilterJson['codtnValueArr'];
      var editAndOrAddArrCounter = this.editFilterJson['andOrAddArrCounter'];
      this.andOrAddArr = editAndOrAddArrCounter; // set and or array counter 

      var editOperatorNameArrLst = this.editFilterJson['operatorNameArrLst'];
      var editselectedInputFieldIndx = this.editFilterJson['selectedInputFieldIndx'];
      var editIsDateArr = this.editFilterJson['isDateArr'];

      var selectedFilterName = this.editFilterJson['selectedFilterName'];
      this.setEditselectedFilterName(selectedFilterName);

      this.setEditselectedInputFieldIndx(editselectedInputFieldIndx);
      var editIndexArrayForPushAndOrAddArr = this.editFilterJson['indexArrayForPushAndOrAddArr'];
      this.indexArrayForPushAndOrAddArr = editIndexArrayForPushAndOrAddArr;
      //console.log('editIndexArrayForPushAndOrAddArr>>129',editIndexArrayForPushAndOrAddArr);
      var filterName = "";
      var dummyDate: any;
      var dummyFrmToDate:any = [];

      for (var i = 0; i < editFieldNameArrLst.length; i++) {
        //Changes To get Date Object if datatype is date- Start
        if (editOperatorNameArrLst[i] == "BETWEEN" && editIsDateArr[i] == true) {
          dummyFrmToDate[0] = this._searchMenuService.getDateObj(editFilterValueArrLst[i][0]);
          dummyFrmToDate[1] = this._searchMenuService.getDateObj(editFilterValueArrLst[i][1]);
          this.setBtwnFiltertextValue(dummyFrmToDate, i);
        }
        else if (editOperatorNameArrLst[i] == "BETWEEN" && editIsDateArr[i] == false) {
          this.setBtwnFiltertextValue(editFilterValueArrLst[i], i);
        } else if (editOperatorNameArrLst[i] != "BETWEEN" && editIsDateArr[i] == true) {
          dummyDate = this._searchMenuService.getDateObj(editFilterValueArrLst[i]);
          this.setFiltertextValue(dummyDate, i);
        } else if (editOperatorNameArrLst[i] != "BETWEEN" && editIsDateArr[i] == false) {
          this.setFiltertextValue(editFilterValueArrLst[i], i);
        }
        //Changes To get Date Object if datatype is date- End

        //console.log('editIsDateArr filtertextValue147[', this.filtertextValue, ']');
        this.filterValueArrLst[i] = editFilterValueArrLst[i];

        if (editisValueCheckBoxStatusArr instanceof Array) {
          this.isValueCheckBoxStatusArr[i] = true;
        }
        else {
          this.isValueCheckBoxStatusArr[i] = true;
        }
        this.setFileldValueO(editFieldNameArrLst[i], i);
        this.fieldNameArrLst[i] = editFieldNameArrLst[i];
        this.setOperatorO(editOperatorNameArrLst[i], i);
        this.operatorNameArrLst[i] = editOperatorNameArrLst[i];
        this.setPromptValueO(editPromtValuOptArr[i], i);
        this.promtValuOptArr[i] = editPromtValuOptArr[i];
        if (editPromtValuOptArr[i] == "Prompt") {
          this.promptSelField[i] = true;
        }
        if (editCodtnValueArr[i] != undefined)//it comes undefined at last index, so made it empty
        {
          this.setAndOrValueO(editCodtnValueArr[i], i);
          this.codtnValueArr[i] = editCodtnValueArr[i];
        } else {
          editCodtnValueArr[i] = "";
          this.setAndOrValueO(editCodtnValueArr, i);
          this.codtnValueArr[i] = editCodtnValueArr[i];
        }
        if (editPromtValuOptArr[i] == "Prompt") {
          filterName += editFilterNamesArrLst[i] + '?';
          //console.log('filterName11', filterName);
        }
        else if (editPromtValuOptArr[i] == "Value") {
          if (editFilterNamesArrLst[i] != '' && editFilterNamesArrLst[i] != undefined) {
            filterName += editFilterNamesArrLst[i];
            //console.log('filterName22', filterName);

          } else {
            filterName += "";//NL
            //console.log('filterName33', filterName);

          }
        }
        this.isDateArr[i] = editIsDateArr[i];
        //2803
        //this.indexArrayForPushAndOrAddArr[i] = editIndexArrayForPushAndOrAddArr[i];
      }
      this.setFilterName(filterName);
      this.setRemoveButtonVisible(true);
    }
  }
  //for Edit filter Data -END
  ngOnChanges() {
    //console.log('isCustomFilter ngOnChanges>>', this.isCustomFilter);
    //console.log('editFilterJson ngOnChanges>>', this.editFilterJson);
  }

  getFieldValue(a:any) {
    //console.log('::In getFieldValue::a== ', a,' this.fileldValueO[a]>', this.fileldValueO[a],this.filtertextValue,'filterValueArrLst>',this.filterValueArrLst);
    delete this.filterValueArrLst[a];
    this.filtertextValue[a] = ""; //Edited on 05032019 made empty on field value selection changed
    this.fieldNameArrLst[a] = this.fileldValueO[a];
    //console.log("event this.fieldNameArrLst[", a, "]", this.fieldNameArrLst[a]);
    this.isDateArr[a] = false;
    if (this.fieldTypeMap[this.fileldValueO[a]] == "date") {
      this.isDateArr[a] = true;
      //console.log("IsDate ", this.isDateArr[a], this.isDateArr);
    }
  }
  getOperatrValue(a:any) {
    var operatrValue = this.operatorValueO[a];
    this.operatorNameArrLst[a] = this.operatorNameMap[operatrValue];
    //console.log("event this.operatorNameArrLst[", a, "]", this.operatorNameArrLst[a]);
  }

  getTextValue(a:any) {
    if (this.promtValuOptArr[a] != 'Prompt') {
      this.promtValuOptArr[a] = "Value"; // To set selection "Value if not selected"
      if (this.fieldTypeMap[this.fileldValueO[a]] == "date") {
        // console.log('getTextValue is date!!');
        this.filterValueArrLst[a] = this.datePipe.transform(this.filtertextValue[a], this.dateFormat); //
      }
      else {
        this.filterValueArrLst[a] = this.filtertextValue[a];
      }
      //console.log("event this.filterValueArrLst", this.filterValueArrLst);
      this.isValueCheckBoxStatusArr[a] = true;
    }
  }

  getBtwnTextValue(a:any) {
    if (this.promtValuOptArr[a] != 'Prompt') {
      this.promtValuOptArr[a] = "Value"; // To set selection "Value if not selected"
      if (this.filterBtwntextValueFrm[a] != undefined && this.filterBtwntextValueFrm[a] != empty) {
        if (this.fieldTypeMap[this.fileldValueO[a]] == "date") {
          this.filterBtwntextValueArr[0] = this.datePipe.transform(this.filterBtwntextValueFrm[a], this.dateFormat);
        } else {
          this.filterBtwntextValueArr[0] = this.filterBtwntextValueFrm[a];
        }
      }
      if (this.filterBtwntextValueTo[a] != undefined && this.filterBtwntextValueTo[a] != empty) {
        if (this.fieldTypeMap[this.fileldValueO[a]] == "date") {
          this.filterBtwntextValueArr[1] = this.datePipe.transform(this.filterBtwntextValueTo[a], this.dateFormat);
        } else {
          this.filterBtwntextValueArr[1] = this.filterBtwntextValueTo[a];
        }
      }
      var newArr = this.filterBtwntextValueArr.slice(0); //coppied the array to avoid reference problem
      this.filterValueArrLst[a] = newArr;
      this.isValueCheckBoxStatusArr[a] = true;
      //console.log("event this.filterValueArrLst", this.filterValueArrLst);
    }
  }

  selctprmtCondition(a:any) {
    var optnValue = this.promptValueO[a];
    this.promtValuOptArr[a] = optnValue;
    if (this.promtValuOptArr[a] == 'Prompt') {
      this.filterValueArrLst[a] = ""; //to set filter value empty at index when Prompt selected
      this.isValueCheckBoxStatusArr[a] = true;
      this.promptSelField[a] = true;

      this.filterName = this.filterName + '?';
      this.promCount++;
    } else {
      this.promptSelField[a] = false;
    }
    //console.log("this.promtValuOptArr[", a, "]", this.promtValuOptArr[a]);
    return
  }

  onSelectAndOR(a:any) {
    var codtnValue = this.andOrValueO[a];
    var andOrAddArrFlag: boolean = false;
    this.codtnValueArr[a] = codtnValue;
    if (this.fieldNameArrLst[a] != "" && this.fieldNameArrLst[a] != undefined && this.fieldNameArrLst[a] != empty) {
      if (this.codtnValueArr[a] == 'And' || this.codtnValueArr[a] == 'Or') {
        for (var indx = 0; indx < this.indexArrayForPushAndOrAddArr.length; indx++) {
          if (this.indexArrayForPushAndOrAddArr[indx] != a) {
            andOrAddArrFlag = true;
          }
          else {
            andOrAddArrFlag = false;
            break;
          }
        }
        if (andOrAddArrFlag == true) {
          this.isAdded++;
          this.andOrAddArr.push("" + this.isAdded);
          // console.log('andOrAddArrCounter==', this.andOrAddArr);
          this.promptSelField.push(false);
          this.isDateArr.push(false);//555
          this.indexArrayForPushAndOrAddArr.push(a);
        }
      }
    }
    else {
      this.andOrValueO[a] = "";
      window.alert('No Filter Expression Is Created !');
    }
    return;
  }

  onCustFiltrDone() {
    if (this.andOrAddArr.length > 1) {
      console.log('this.andOrAddArr.length is greater than 1 so removing the isvalucheckboxarr indexes');
      var dummy = this.isValueCheckBoxStatusArr[0];
      this.isValueCheckBoxStatusArr = [];
      this.isValueCheckBoxStatusArr[0] = dummy;
    }

    if (this.promtValuOptArr.length < 1) {
      this.promtValuOptArr[0] = "Value"; //if promtValuOptArr is empty then by default put
    }

    let filterNames = this.filterName;
    this.filterNameArrForExprMap[0] = this.filterName;
    if (filterNames.length < 1) {
      window.alert("FilterName is Empty!");
    }
    else {
      if (filterNames.includes('?')) {
        let filterNameArr:any = [];
        filterNameArr = filterNames.split('?');
        for (var i = 0; i < filterNameArr.length; i++) {
          var filter = "";
          if (filterNameArr[i] != "") {
            filter = filterNameArr[i];
            this.filterNamesArrLst[i] = filter;
            console.log("IN THE LOOP filter");
          }
        }
      }
      else {
        this.filterNamesArrLst[0] = this.filterName;
      }

      if (this.fieldNameArrLst.length != this.filterNamesArrLst.length) {
        for (var i = 0; i < this.fieldNameArrLst.length; i++) {
          try {
            if (this.filterNamesArrLst[i] == undefined) {
              console.log('filterNamesArrLst[', i, '] is undefined');
              this.filterNamesArrLst[i] = "";
            }
          }
          catch
          {
            this.filterNamesArrLst[i] = "";
          }
        }
      }
      //Addes to put default selection as 'Value' in promtValuOptArr 
      if (this.promtValuOptArr.length < this.fieldNameArrLst.length) {
        // console.log('less than lenght valu propmt>>');
        for (var i = 0; i < this.fieldNameArrLst.length; i++) {
          if (this.promtValuOptArr[i] != "Prompt") {
            this.promtValuOptArr[i] = "Value";
          }
        }
      }
      var allCustomFilterJson:any = {};
      allCustomFilterJson['filterNameArrForExprMap'] = this.filterNameArrForExprMap;

      allCustomFilterJson['filterValueArrLst'] = this.filterValueArrLst;
      console.log('found filterValueArrLst.==', this.filterValueArrLst);

      allCustomFilterJson['isValueCheckBoxStatusArr'] = this.isValueCheckBoxStatusArr;
      console.log('found isValueCheckBoxStatusArr.==', this.isValueCheckBoxStatusArr);

      allCustomFilterJson['fieldNameArrLst'] = this.fieldNameArrLst;
      allCustomFilterJson['operatorNameArrLst'] = this.operatorNameArrLst;
      allCustomFilterJson['promtValuOptArr'] = this.promtValuOptArr;
      allCustomFilterJson['codtnValueArr'] = this.codtnValueArr;
      allCustomFilterJson['fieldTypeMap'] = this.fieldTypeMap;
      allCustomFilterJson['filterNamesArrLst'] = this.filterNamesArrLst;
      allCustomFilterJson['fieldDispNameMapkeys'] = this.fieldDispNameMapkeys;
      allCustomFilterJson['andOrAddArr'] = this.andOrAddArr;
      allCustomFilterJson['isDateArr'] = this.isDateArr;
      allCustomFilterJson['indexArrayForPushAndOrAddArr'] = this.indexArrayForPushAndOrAddArr;

      if (this.editselectedInputFieldIndx != null && this.editselectedInputFieldIndx != undefined
        && this.editselectedFilterName != "") {
        //console.log('found edited input field index no.==', this.editselectedInputFieldIndx);
        allCustomFilterJson['selectedInputFieldIndx'] = this.editselectedInputFieldIndx;
        allCustomFilterJson['editselectedFilterName'] = this.editselectedFilterName;
      }
      else {
        //console.log('Not found edited input field index no.');
        this.editselectedInputFieldIndx = null;
        allCustomFilterJson['selectedInputFieldIndx'] = null;
        allCustomFilterJson['editselectedFilterName'] = "";
      }
      //console.log('<<<allCustomFilterJson>>', allCustomFilterJson);
      //check filter names are entred properly for every field or not
      if (this.fieldNameArrLst.length == this.filterNamesArrLst.length) {
        for (var i = 0; i < this.andOrAddArr.length; i++) {
          if (this.fieldNameArrLst[i] != undefined && this.fieldNameArrLst[i] != 'undefined') {
            //console.log("field Value for[", i, "] index ", this.fieldNameArrLst[i]);
            if (this.operatorNameArrLst[i] != undefined && this.operatorNameArrLst[i] != 'undefined') {
              //console.log("operator Value for[", i, "] index ", this.operatorNameArrLst[i]);
              if (this.promtValuOptArr[i] == 'Value') {
                if (this.filterValueArrLst[i] != undefined && this.filterValueArrLst[i] != 'undefined') {
                  // console.log('::in onDone Emit::');
                  // this.isClick = true;
                  this.isDoneEmitFlag = true;
                }
                else {
                  this.isDoneEmitFlag = false;
                  window.alert("Please! Provide Values(s) In The Value Textbox(s)");
                }
              }
              else if (this.promtValuOptArr[i] == 'Prompt') {
                // this.isClick = true;
                this.isDoneEmitFlag = true;
              }
            }
            else {
              this.isDoneEmitFlag = false;
              window.alert("Please! Select Appropriate Operator(s) From The Operators List");
            }
          }
          else {
            this.isDoneEmitFlag = false;
            window.alert("No field name is selected is selected!");
          }
        }
      }
      else {
        this.isDoneEmitFlag = false;
        window.alert('Please enter the filter name for all fields!!')
      }
      console.log("isDoneEmitFlag432", this.isDoneEmitFlag);
      if (this.isDoneEmitFlag) {
        this.isClick = true;
        this.onDone.emit(allCustomFilterJson);
      }
    }
    console.log("filterName", this.filterNamesArrLst);
    this.isEditJson = true;//on cancel will go out of edit mode will not access editjson variables
    return;
  }

  // getPhysicalName(fieldNamel:any) {
  //   return fieldName;
  // }

  getPhysicalName(fieldNamel:any) {
    return fieldNamel;
  }

  onCancelClick() {
    console.log('in onCancelClick');
    this.isEditJson = true;//on cancel will go out of edit mode will not access editjson variables
    this.onClose.emit();
  }

  removeFilter() {
    var txt;
    var removeMap:any = {};
    if (confirm("Press a button!")) {
      txt = "OK";
    } else {
      txt = "Cancel";
    }
    if (txt == "OK") {
      removeMap["editselectedInputFieldIndx"] = this.editselectedInputFieldIndx;
      removeMap["editselectedFilterName"] = this.editselectedFilterName;
      this.onRemove.emit(removeMap);
    }
  }

  //Setters and getters -Start
  setBtwnFiltertextValue(filterBtwntextValue: any[], i: number) {
    //console.log('in setBtwnFiltertextValue::', filterBtwntextValue, 'i>>', i);
    this.filterBtwntextValueFrm[i] = filterBtwntextValue[0];
    this.filterBtwntextValueTo[i] = filterBtwntextValue[1];
  }
  setRemoveButtonVisible(booleanValue: boolean): any {
    this.isRemoveBtnVisible = booleanValue;
  }
  setEditselectedInputFieldIndx(editselectedInputFieldIndx: number): any {
    this.editselectedInputFieldIndx = editselectedInputFieldIndx;
  }

  setEditselectedFilterName(selectedFilterName: string): any {
    this.editselectedFilterName = selectedFilterName;
    //console.log('editselectedFilterName>>', this.editselectedFilterName);
  }

  setFiltertextValue(editfiltertextValueArr: any, i: number): any {
    this.filtertextValue[i] = editfiltertextValueArr;
    //console.log('setFiltertextValue>>',this.setFiltertextValue)
  }
  setAndOrValueO(andorArr: any, i: number): any {
    this.andOrValueO[i] = andorArr;
  }
  setPromptValueO(promptValueArr: any, i: number): any {
    this.promptValueO[i] = promptValueArr;
  }
  setFileldValueO(fieldnameArr: any, i: number): any {
    this.fileldValueO[i] = fieldnameArr;
  }
  setOperatorO(editoperator: any[], i: number): any {
    this.operatorValueO[i] = editoperator;
  }
  seteditFilterValueArrLst(editFilterValueArrLst: any[]) {
    this.editFilterValueArrLst = editFilterValueArrLst;
  }
  setFilterName(filterName: string) {
    this.filterName = filterName;
  }
  //Setters and getters -End
}
/*  */