import { Component, OnInit, ViewEncapsulation, ChangeDetectorRef, Output, EventEmitter, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';
import { SearchComponent } from './searchComponent.service';
import { OverlayConfig, Overlay } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { HomePagePopuppanelComponent } from './home-page-popuppanel/home-page-popuppanel.component';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-search-menu',
  templateUrl: './search-menu.component.html',
  styleUrls: ['./search-menu.component.css'],
  encapsulation: ViewEncapsulation.None,
})
export class SearchMenuComponent implements OnInit {
  //public objName = ""; //need to get it by inpuit interface as told by prasad sir
  //Change by sadique on 20-10-2020 [to hide pophelp if objnamefrom contain data] -->
  popHelpDisp:boolean = true;
  public objDtlResonse = "";
  objNameInput = "";
  pophelpFieldsDetails: any;
  pophelpFieldsDetailsMap:any = {};
  @Output() isBackFlag: EventEmitter<any> = new EventEmitter();
  objNameFlag: boolean = false;
  dataSource = "";
  fieldValue = "";
  refId = "";
  randomNo = Math.random();
  pophelpFlag: boolean = false;
  isBrowser!: boolean;//to get browser/mobile 
  @ViewChild('portal', { read: TemplateRef }) _templatePortal!: TemplateRef<any>;
  overlayRef:any;
  filterName!: string;
  tcode!: string;
  objDetailsMap:any = {};
  pluginMetadata:any;
  pophelpDataSource: any;
  headerMenuImg = "/ibase/images/menuImages/web/exportZip.png";
  errorImage = "/ibase/images/menuImages/errMenu.png";
  @ViewChild(HomePagePopuppanelComponent) hmPgComp!: HomePagePopuppanelComponent;
  //By Sainath T. on 03-07-19 [To Set header]
  objDescr: string = "";
  //Added by Sainath T. on 01-NOV-2019 -Start
  dateFormat: string = "";
  isUploadStatus :boolean = false;
  responseData:any = {};
  uploadOverlayRef:any ;
  @ViewChild( 'exportStatus' ) templateUploadStatus!: TemplateRef<any>;
  config = new OverlayConfig(); 
  isOverlay: boolean = false;
  //Added by Sainath T. on 01-NOV-2019 -End
  //Added by Sainath T. on 15-NOV-2019
  pophelpSelectedvalue = "";
  refreshDate:any = new Date();
  callFromJsp: boolean = false;
  //Added by Sainth T. on 28-03-2020 [to get the appl date format form jsp]
  applDateFormatFromJsp = '';
  constructor(private cdr: ChangeDetectorRef, private _searchMenuService: SearchComponent, public overlay: Overlay, private viewContainerRef: ViewContainerRef, public datePipe : DatePipe) 
  { }

  ngOnInit() {
    var themColor = localStorage.getItem('themeColor');
    console.log('In ngOn Init search menu component theme color>>',themColor);
    if(themColor == null || themColor =='null' || themColor.length == 0 )
    {
      themColor = "#7bc6ff"; //fda786- for Sun //7bc6ff-for base
    }
    var rootElem = <HTMLElement>document.querySelector(':root')
    rootElem.style.setProperty('--themeColor', themColor)
    //console.log('AdvanceSearch42>[', this.objName,']');
    this.setPopUpParameters("");
    //this.setObjNameInput(this.objName);
    //console.log('pluginMetadata ngOnInit [', this.pluginMetadata,']');
    var objNameFromJSP = '';
    if (this.pluginMetadata != undefined) 
    {
      if (this.pluginMetadata.compData["objName"] != null) 
      {
        objNameFromJSP = this.pluginMetadata.compData["objName"];
      }
      //Added by Sainath T. on 28-03-2020-Start
      this.applDateFormatFromJsp = this.pluginMetadata.compData["APPL_DATE_FORMAT"];
      console.log('applDateFormatFromJsp>>'+this.applDateFormatFromJsp);
      if( this.applDateFormatFromJsp != null && this.applDateFormatFromJsp.trim().length > 0 )
      {
         this._searchMenuService.setApplDateFormatFromJsp(this.applDateFormatFromJsp);
      }
      //Added by Sainath T. on 28-03-2020-End
    }

    console.log("the objNameFromJSP :[" + objNameFromJSP,']');
    if (objNameFromJSP != null && objNameFromJSP != 'null' && objNameFromJSP != '' && objNameFromJSP.length > 0 && objNameFromJSP != undefined && objNameFromJSP != 'undefined') {
      this.objNameInput = objNameFromJSP;
      this.callFromJsp = true;
      this.popHelpDisp = false;

      this.getObjectXmlDetails(objNameFromJSP);
      //this.objName = this.objNameInput;
    }
    let index = window.location.pathname.indexOf('E12BROWSER');
    if (index > -1) {
      this.isBrowser = true;
    }
    //Added by Sainath T. on 01-NOV-2019 [to get date format]
    this.dateFormat = this._searchMenuService.getDateFormat();
  }

  ngOnChanges() {
    this.setPopUpParameters("");//for suggestions
  }
  //On object name selection
  submit() {
    //console.log("the code :[" + this.objNameInput, ']this.objNameFlag>[', this.objNameFlag,']');
    if (this.objNameInput) {
      //this.objName = this.objNameInput;
      this._searchMenuService.setLoading(true);
      this.getObjectXmlDetails(this.objNameInput);//call will go to objdetails if no error flag will true then next
    }
    else {
      //console.log('submit method objNameFlag[', this.objNameFlag,']');
      this.objNameFlag = false;
      window.alert('Please Enter Object Name!!');
    }
  }

  getObjectXmlDetails(objName: string) {
    console.log("the getObjectXmlDetails :" + objName);
    //To get The header label -Start
    this.objDescr = objName;
    try
    {
      if(this.pophelpDataSource)
      {
        var detail = this.pophelpDataSource.DETAILS;
        if(detail)
        {
          for(let det of detail)
          {
            if(det.Obj_Name == objName && det.Descr != undefined)
            {
              this.objDescr = det.Descr;
              console.log('this.headerLabe[',this.objDescr,']');
            }
          }
        }
      }
    }
    catch{
      console.log('Exception while getting Header label');
    }
    //To get The header label -End
    var paramMap:any = {};
    var paramString: string;
    paramMap["ACTION"] = "OBJ_DETAILS";
    paramMap["OBJ_NAME"] = objName;
    paramMap["PAGE_CTX"] = "1";
    paramMap["dummyInt"] = "" + Math.random();
    paramMap["CALLED_FROM"] = "ANG_SEARCH_MENU";

    paramString = this._searchMenuService.getEncodedParamString(paramMap);
    //console.log("the paramString :" + paramString);
    this._searchMenuService.getObjDetailResponse(paramString).subscribe(
      (data:any) => {
        if (data) {
          var objDtlResonse = data;
          //console.log('objDtlResonse==>[' + objDtlResonse + ']');
          if (objDtlResonse != '' && objDtlResonse != undefined) {
            if (objDtlResonse.indexOf('Errors') != -1 || objDtlResonse.indexOf('ERR_MSG') != -1) {
              //console.log("objDtlResonse108");
              this.objNameFlag = false;
              alert(objDtlResonse.substring(objDtlResonse.indexOf(":") + 1, objDtlResonse.length));
              this._searchMenuService.setLoading(false);
              document.getElementById("Search_Menu" + this.randomNo)!.style.display = "";
            } else {
              //console.log('in else objDtlResonse114');
              this.objDtlResonse = objDtlResonse;
              this.objDetailsMap[this.objNameInput] = this.objDtlResonse;
              this.objNameFlag = true;
              this._searchMenuService.setLoading(false);
              document.getElementById("Search_Menu" + this.randomNo)!.style.display = "none";
            }
          }
        }
      }
    );

    var pophelpDetailsParamMap:any = {};
    var pophelpDetailsParamString: string;

    pophelpDetailsParamMap['OBJ_NAME'] = objName;
    pophelpDetailsParamMap['ACTION'] = "OBJ_POPHELPINFO_ALL";
    pophelpDetailsParamMap['OBJ_TYPE'] = "";
    pophelpDetailsParamMap['dummyInt'] = Math.random();
    pophelpDetailsParamMap['PKVLAUE'] = "";
    pophelpDetailsParamMap['EDIT_FLAG'] = "";
    pophelpDetailsParamString = this._searchMenuService.getEncodedParamString(pophelpDetailsParamMap);
    this._searchMenuService.getPopHelpFields(pophelpDetailsParamString).subscribe(
      (data:any) => {
        if (data) {
          this.pophelpFieldsDetails = data;
          //console.log('pophelpFieldsDetails==>[' + this.pophelpFieldsDetails + ']');
          //console.log('pophelpFieldsDetails==>[' + this.pophelpFieldsDetails.length + ']');
          this.pophelpFieldsDetailsMap[this.objNameInput] = this.pophelpFieldsDetails;
          if (this.pophelpFieldsDetailsMap[this.objNameInput] != null && this.pophelpFieldsDetailsMap[this.objNameInput].length > 0) {
            //console.log('Call From Search-menu Component SetpophelpFields');
            try {
              this.hmPgComp.setPophelpFields(this.pophelpFieldsDetailsMap[this.objNameInput]);
            }
            catch{
              console.log('Could Not Access Setpophelp Method of child');
            }
          }
        }
      }
    );
    console.log('ruturn flag', this.objNameFlag);
  }

 /*  setObjNameInput(objNameFromJSP: any) {
    this.objNameInput = objNameFromJSP;
  } */

  openSuggest() {
    this.pophelpFlag = true;
    this.setPopUpParameters("true");
  }

  onSelectionChange(event:any) {
    console.log('on change selection event', event);
	//Changed by Sainath T. on 01-NOV-2019  
    //this.objNameInput = event.value;
    this.pophelpSelectedvalue = event.value;
  }

  onDone() 
  {
  	//Added by Sainath T. on 01-NOV-2019 -Start
    console.log('on done pophelpSelectedvalu [' + this.pophelpSelectedvalue + ']');
    this.objNameInput = this.pophelpSelectedvalue;
    this.overlayRef.dispose();
    this.pophelpSelectedvalue = "";
    //Added by Sainath T. on 01-NOV-2019 -End
  }

  onCancel() {
    console.log('on onCancel', this.objNameInput);
    this.pophelpSelectedvalue = "";
    this.overlayRef.dispose();
  }

  setPopUpParameters(pophelpFlag:any) {
    var paramMap:any = {};
    var paramString = "";
    this.refId = "OBJ_NAME__SCOPE";

    paramMap["OBJ_NAME"] = "";
    paramMap["ACTION"] = "AUTO_SEARCH_POPHELP";
    paramMap["FIELD_NAME"] = this.refId;
    paramMap["SQL_INPUT"] = "";
    paramMap["EDITOR_ID"] = "";
    paramMap["FORM_NO"] = "";
    paramMap["PARAMXML"] = "";
    paramMap["PKVLAUE"] = "";
    paramMap["EDIT_FLAG"] = "";
    paramMap[this.refId] = this.objNameInput;
    paramString = this._searchMenuService.getEncodedParamString(paramMap);
    //console.log('this.pophelpDataSource>>', this.pophelpDataSource);
    this.dataSource = "/ibase/RIAWizardHandlerServlet?" + paramString;
    this._searchMenuService.getPophelpData(this.dataSource, this.refId, false, this.objNameInput).subscribe(
      (data:any) => {
        if (data) {
          this.pophelpDataSource = data;
          //console.log('pophelpDataSource==>[' + this.pophelpDataSource + ']');
        }
      }
    );
    this.fieldValue = this.objNameInput;
    this.filterName = this.refId + '_' + this.objNameInput;
    
    if (pophelpFlag == "true") {
      setTimeout(() => this.createOverlay(), 200);
    }
  }

  onSuggChangeValue(event:any) {
    //console.log("onChangeValue event get called in filter - input ", event);
    if (event.length > 2) {
      this.setPopUpParameters("");
    }
    //this.setObjNameInput(event);
    this.objNameInput = event;

  }

  changeSuggSelection(event:any, idx:any) {
    //console.log("changeSuggSelection event get called in filter event.value>>", event.detail.id);
    //this.setObjNameInput(event.detail.id);
    this.objNameInput = event.detail.id;
  }

  createOverlay() {
    var config = new OverlayConfig();
    var width = '500px';
    var top = this.isBrowser ? '0px' : '40px';
    var height = 'auto';
    var left = " calc(100% - 360px)";
    console.log('SetTimeOut start 2');

    config.hasBackdrop = true;
    config.positionStrategy = this.overlay.position()
      .global()
      .centerHorizontally()
      .width(width)
      .left(left)
      .top(top)
      .height(height);
    const templatePortal = new TemplatePortal(
      this._templatePortal,
      this.viewContainerRef
    );
    console.log('SetTimeOut start 4');

    this.overlayRef = this.overlay.create(config);
    this.overlayRef.attach(templatePortal);
  }

  /*Added by Sainath T. on 01-NOV-2019 [Add method for data export to zip & download file] Start*/
  exportStatus(date: any)
  {
    console.log('Inside exportStatus method.............',date);
    this.getbckGrounJobData(date, true);
  }

  getbckGrounJobData(date:any, isOverlay:any):any
  {
    console.log('Inside getbckGrounJobData......');
    this.isOverlay = isOverlay ;
    var paramMap:any = {};
    var paramString = "";
    paramMap["from_date"] = date;
    paramMap["action"] = "fromExcel";
    paramString = this._searchMenuService.getEncodedParamString(paramMap);
    this._searchMenuService.uploadStatus(paramString)
    .subscribe((data:any) => {
      if (data) {
        try {
         this.responseData['data'] = JSON.parse(data);
        } catch (error) {
          console.log('Exception while emiting.....');
        }
        console.log('Response data from UploadTemplate Servlet ',this.responseData);
        this.isUploadStatus = true;
        if( this.isOverlay )
        {
          setTimeout(()=>
          {
            this.uploadStatusOverlay(); 
          },100);

        }
      }
    }
    );
  }

  uploadStatusOverlay() 
  {
    console.log("Creating overlay for uploadStatus ::")
    setTimeout(()=>
    {
      this.setPosition();
    },200);
    const templateUploadStatus = new TemplatePortal(
    this.templateUploadStatus,
    this.viewContainerRef
    );
    this.uploadOverlayRef = this.overlay.create( this.config );
    this.uploadOverlayRef.attach( templateUploadStatus );  
  }

  setPosition()
  {
    let positionElem = document.getElementsByClassName( 'frameStyle' );
    //console.log('positionElem.......',positionElem);
    let position : any;
    if(positionElem)
    {
      position = document.getElementsByClassName( 'frameStyle' )[0].getBoundingClientRect();
    }
    //let position = document.getElementById("frameStyle").parentElement.getBoundingClientRect();  //dashboardDiv
    var width = position.width + 7;
    var top = position.top;
    var height = position.height; //+34
    var left = position.left;
    var bottom = position.bottom;
    var right = position.right;
    console.log('position:h:w:t:l:r:b:',height,'',width,'',top,'',left,'',right,'',bottom);
    this.config.hasBackdrop = false;
    console.log( 'config & templateUploadStatus ', this.config, this.templateUploadStatus );
    this.config.positionStrategy = this.overlay.position()
      .global()
      .width( width )
      .top( top )
      .bottom( bottom )        
      .height( height )
      .left( left )
      .right( right );
  }
  
  onUploadStatusCancle()
  {
    this.isOverlay = false;
    this.uploadOverlayRef.dispose();
  }
  changeDate( event: MatDatepickerInputEvent<Date> )
  {  
      console.log('selected change date--',event); 
      //Changed by Sainath T. on 04-03-2020 [For refresh button]
      if(event && event != undefined)
      {
        this.refreshDate = event.value;
      }
      var date = this.datePipe.transform(this.refreshDate, this.dateFormat);
      this.getbckGrounJobData(date,false);
  }
  /*Added By Sainath T on Added by Sainath T. on 01-NOV-2019 [Add method for data export to zip & download file] End*/
}
