import { Component, OnInit,OnChanges, Input, Output, EventEmitter, ElementRef,ViewChild,ViewEncapsulation, ViewContainerRef, TemplateRef } from '@angular/core';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { DatePipe } from '@angular/common';
import { FilterInfo } from './filter-info.model';
import { DashboardService } from '../../dashboard.service';

import { Overlay,OverlayConfig } from '@angular/cdk/overlay';
import { ComponentPortal,Portal,TemplatePortal } from '@angular/cdk/portal';
//import {FormControl} from '@angular/forms';
//import { BISIntentService } from '../../../bis-assistant/bis-services/bis-intent.service';
import { AppDateAdapter, APP_DATE_FORMATS } from '../../../search-menu/date.adapter';
import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';

@Component({
  selector: 'filter-input',
  templateUrl: './filter-input.component.html',
  styleUrls: ['./filter-input.component.css'],
  providers:[{
      provide: DateAdapter, useClass: AppDateAdapter
  },
  {
    provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
  },
  DatePipe
],
  encapsulation: ViewEncapsulation.Emulated
})
export class FilterInputComponent implements OnInit {
    
  constructor(
          //public intentService : BISIntentService,
          public datePipe:DatePipe,public overlay: Overlay,private viewContainerRef: ViewContainerRef,private dashboardService: DashboardService) { }

  @Input() filterInfo : FilterInfo | any;
  @Input() dateFormat : string | any;
  @Output() valueChange = new EventEmitter;
  @Input() fromDate :Date | any ;
  @Input() toDate :Date | any ;
  
  @ViewChild( 'portal' ) templatePortal: TemplateRef<any> | any;
  @ViewChild("monthPickerEl") monthPickerEl : ElementRef | any;
  overlayRef: any;
  dataSource: any;
  filterInput: any;
  refId: any;
  selectedVal: any[] =[];
  isAllChecked: any;

  checkedData: any[] = [];
  
  filterType: string | any;
  filterValue: any;
  filterDefValue: string | any;
  filterName: string | any;
  filterDescr: string | any; 
  filterId: string | any;
  filterFieldName: string | any;
  filterModName: string | any; 
  filterShowOnTitle: string | any; 
  filterValues: any;
  filterMandatory: boolean | any;
  maxDate = new Date(); //date upadted
  
  key_string:string | any;
  auto_fill_len:string | any;
  multi_opt:string | any;
  obj_name:string | any;
  isPopHelp:boolean | any;
  help_option:string | any;
  layout: any; 
  chipData: any=[];
  isBrowser: boolean | any;
  isAllSelected: any;
  disabled: any;
  hidden:boolean | any;

  readOnly: boolean | any;

  @Input() filterExprInput: any;  
  filterExprFieldName: any;
  @Output() populateExprData = new EventEmitter;
 
  ngOnInit() {
      console.log('filterInfo--',this.filterInfo);
      if( this.filterInfo )
      {
        this.filterType = this.filterInfo.type ? this.filterInfo.type : '1';
        this.filterDefValue = this.filterInfo.default_value ? this.filterInfo.default_value : '';
        this.filterName = this.filterInfo.col_name ? this.filterInfo.col_name : '';
        this.filterDescr = this.filterInfo.col_descr ? this.filterInfo.col_descr : '';
        this.filterId = this.filterInfo.col_id ? this.filterInfo.col_id : '';
        this.filterMandatory = this.filterInfo.mandatory == 'Y' ? true : false;
        this.filterValues = this.filterInfo.values ? this.filterInfo.values : '';
        this.filterValue = this.filterDefValue;
        this.layout = this.filterInfo.layout;
        this.filterExprFieldName = this.filterInfo.filter_expr ? this.filterInfo.filter_expr : '';
        this.hidden = this.filterInfo.hidden == 'Y' ? true : false;
        console.log('filterStringValue==>',this.filterExprFieldName);
        
        this.filterInfo.changedValue = this.filterValue; 

        if(this.filterType=='4'){
            this.filterValue = this.dashboardService.getDefaultDate(this.filterInfo.default_value);
            this.filterInfo.changedValue = this.formatDate(this.filterValue);
            this.filterInfo.default_value = this.formatDate(this.filterValue);            
        }else if(this.filterType=='6'){
            this.filterValue = this.dashboardService.getDefaultYear(this.filterInfo.default_value);
            this.filterInfo.changedValue = this.filterValue;
            this.filterInfo.default_value = this.filterValue;
            
            var defDate = new Date();
            defDate.setFullYear(this.filterValue);
            this.filterValue = defDate;
        }
        else if(this.filterType=='5'){
            this.filterValue = this.dashboardService.getDefaultMonth(this.filterInfo.default_value);
            this.filterInfo.changedValue = this.filterValue;
            this.filterInfo.default_value = this.filterValue;
        }
        else if(this.filterType=='7')
        {
            this.filterInfo.default_value = this.filterValue;
            this.filterValue =this.dashboardService.getDefaultSite(this.filterInfo.default_value);
            //this.filterInfo.default_value = this.filterValue;
            this.filterInfo.changedValue= this.filterValue;
            console.log('filter type 7',this.filterValue,this.filterInfo.default_value);
         }
        
        console.log('filterValue ',this.filterValue);
        
        this.key_string = this.filterInfo.key_string ? this.filterInfo.key_string : '';
        this.auto_fill_len = this.filterInfo.auto_fill_len ? this.filterInfo.auto_fill_len : '';
        this.multi_opt = this.filterInfo.multi_opt ? this.filterInfo.multi_opt : '';
        this.obj_name = this.filterInfo.obj_name ? this.filterInfo.obj_name : (this.filterInfo.mod_name ? this.filterInfo.mod_name : '');
        this.isPopHelp = this.filterInfo.is_pophelp;
        this.help_option = this.filterInfo.help_option ? this.filterInfo.help_option : '';
      }
      if(this.isPopHelp){       
        if(!this.key_string){
          this.dataSource = "/ibase/PopupDataServlet?FIELDNAME="+this.filterName+"&OBJ_NAME="+this.obj_name+"&OUTPUT_FORMAT=JSON&KEYSTRING=dummy";
        }else {
          //Temporary  
          //this.refId = this.key_string.replace(":", '');
          this.dataSource = "/ibase/PopupDataServlet?FIELDNAME="+this.filterName+"&OBJ_NAME="+this.obj_name+"&OUTPUT_FORMAT=JSON&KEYSTRING="+this.key_string;
        }
      }
      this.emitValueChg();
      
      let index = window.location.pathname.indexOf('E12BROWSER');
      
      if(index > -1){
          this.isBrowser = true;
      }
      /*
      if(this.filterValue && typeof(this.filterValue)=='string'){
          this.filterValue = this.filterValue.replace(",",'');
          this.chipData.push({ display: this.filterValue, value: this.filterValue });
      }
	  */      
      if(this.multi_opt == '1' && this.filterValue && typeof(this.filterValue)=='string'){
          this.filterValue.split(",").map( (chipValue: any)=>{
	        //   this.chipData.push(
	        //      { display: chipValue, value: chipValue }
	        //   );
            this.chipData.push(
                { display: chipValue, value: chipValue }
            );
             
          });
      }
      
      console.log('filterValue ',this.filterValue);
  }

  ngOnChanges(){
      if(this.toDate==null){
          this.toDate=this.maxDate;
      }
  }
  changeChipValue( value: string ) {
      console.log( 'selected--', value, this.filterValue );
      this.filterValue = value.split( "," ).filter( val => { return val.trim() } );
      console.log( 'on spliting', this.filterValue );
      this.filterInfo.changedValue = this.filterValue;
      this.emitValueChg();
  }
  
  changeValue()
  { 
      console.log('selected--',this.filterValue);
      this.filterInfo.changedValue = this.filterValue;
      this.emitValueChg();
  }
  
  changeSelection(detail: any)
  {
      console.log('change selection--',detail);
      //this.filterValue = detail.id;
      this.filterValue = detail.detail.id; //changed by chitranga tandel
      
      this.filterInfo.changedValue = this.filterValue;
      this.emitValueChg();
  }

  changeDate( event: MatDatepickerInputEvent<Date> )
  {  
      console.log('selected change date--',event);
      console.log('selected filterValue --',this.filterValue);
      console.log('selected dateFormat --',this.dateFormat);
      this.filterInfo.changedValue = this.formatDate(this.filterValue);
      
      this.emitValueChg();
  }
  
  formatDate(dateValue : any) : any
  {
      var changedValue: any ='';
      if( this.dateFormat )
      {
          try{
              
              changedValue = this.datePipe.transform(dateValue, this.dateFormat);
          }
          catch(e){
             // changedValue = this.datePipe.transform(dateValue, 'dd/MM/yyyy');
              changedValue = this.datePipe.transform( new Date(), this.dateFormat );
          }
      }
      else
      {
          changedValue = this.datePipe.transform(dateValue, 'dd/MM/yyyy');
      }
      return changedValue;
  }
  createOverlay()
  {
      var config = new OverlayConfig();
      var width = '500px';
      var top = this.isBrowser ? '100px' : '40px';
      var height = 'auto';
      var left = "calc(100% - 350px)";

      config.hasBackdrop = true;
      console.log( 'config & templatePortals ', config, this.templatePortal );

      /*  
      if ( this.clientWidth < 640 ) {
          width = '100%';
          top = '0';
          height = '100%';
      }
      */

      config.positionStrategy = this.overlay.position()
          .global()
          .centerHorizontally()
          .width( width )
          .left( left )
          .top( top )
          .height( height );

      const templatePortal = new TemplatePortal(
          this.templatePortal,
          this.viewContainerRef
      );

      this.overlayRef = this.overlay.create( config );
      this.overlayRef.attach( templatePortal );
  }
  
  openPophelp()
  {
      //Added by Kamal.P to pass filterExpression value at filterScreen component START
      if(this.filterExprFieldName)
      {
           this.populateExprData.emit(this.filterExprFieldName); //Used at filter-screen.component
           console.log('filterExpresionResult==>',this.filterExprInput);
      }  
      //Added by Kamal.P to pass filterExpression value at filterScreen component END
      this.createOverlay();
  }
  
  closePohelp()
  {
      this.overlayRef.dispose();
  }
  
  setValue(value: any)
  {
      this.filterValue = value;
      console.log('Emitted Value:',this.filterValue);
      this.closePohelp();
      
      this.filterInfo.changedValue = this.filterValue;

      this.chipData=[];
      for(let chipValue of this.filterValue  ){
        this.chipData.push(
            { display: chipValue, value: chipValue }
        );
      }
      console.log('chipData',this.chipData);
     
      this.emitValueChg();
  }
  
  emitValueChg(){
      this.valueChange.emit(this.filterInfo);
  }
  
  onChangeValue(value: any)
  {
      console.log("onChangeValue event get called in filter - input " , value);
      this.filterValue = value;
  }
  
  toDateMethod( dateStr: any ) 
  {
      console.log('fromDate::::::::',dateStr);
      var splitDate =dateStr.split("/");
      console.log('splitDate::: :',splitDate);
      let firstdate= splitDate[0];
      let month= splitDate[1];
      dateStr=month+'/'+firstdate+'/'+splitDate[2];
      console.log('updated fromDate::: :',dateStr);
      var datePipe = new DatePipe( "en-US" );
      var date: any= datePipe.transform(dateStr, 'dd/MM/yyyy' );
      console.log('dueDate::: :',date);
      var parts = date.split( "/" );
      console.log('parts::: :', parts);
 //     return new Date( parts[2], parts[1]-1,parts[0]  );
  }
  
    
  changeSingleValues(value: any)
  {
      console.log('change value selection--',value);
     // this.filterValue = detail.id;
      
      this.filterInfo.changedValue = value;
      this.emitValueChg();
  }
  
  changeMultipleValue(value: any)
  {
      console.log('change multipl value filter value ',this.filterValue);
      var index = this.selectedVal.indexOf(value);
      if(index > -1){
          this.selectedVal.splice(index, 1);
      }else {
           this.selectedVal.push(value);

      }
      this.filterInfo.changedValue = this.selectedVal;
      console.log('change multiple value ',value);
      console.log('---Selected Multiples Values  are END--',this.selectedVal);
      
  }
  
  selectAll(valuesArray: any){
      this.isAllSelected = !this.isAllSelected;
      var allSelectedVal: any=[];
      this.disabled=!this.disabled;
      for(let values of valuesArray){
          allSelectedVal.push(values.data);
      }
      this.filterInfo.changedValue = allSelectedVal;
      console.log('inside select all>>> ',allSelectedVal,this.filterInfo.changedValue);
  }

  changeMonthValues(value: any)
  {
      var changedValue = this.formatMonth(value);
      console.log('change month value selection--',changedValue);
      this.filterInfo.changedValue = changedValue;
      this.emitValueChg();
  }
  
  changeYearValues(value: any)
  {
      console.log('change year value selection--',value);
      this.filterInfo.changedValue = value;
      this.emitValueChg();
  }
 
  elemRef: any;
  openCalender($event: any)
  {
      this.elemRef = document.getElementsByClassName('mat-calendar-period-button');
      if(this.elemRef){
          setTimeout (() => {
              this.elemRef[0].disabled = true;
          }, 100)
      }
      console.log('the calender is open',this.elemRef);
  }
  ngAfterViewInit(){
      console.log('monthPickerEl ::',this.monthPickerEl);
      if(this.filterType=='5' && this.monthPickerEl)
      {
          console.log('this.filterValue ',this.filterValue);
          var dateVals = this.filterValue.split('/');
          var dateObj = new Date();
          try {              
              dateObj.setMonth(Number(dateVals[0]) - 1);
              dateObj.setFullYear(Number(dateVals[1]));
          } catch(e){
              console.log('Exception in FilterInputComponent',e);
          }
          console.log('dateObj ::',dateObj);
          var displayValue = this.datePipe.transform(dateObj, 'MMM yyyy');  
          this.monthPickerEl.nativeElement.querySelector('input').value = displayValue;
      }
  }
  
  formatMonth(monthString : string)
  {
      var monthStr = '';
      if(monthString && monthString.indexOf("/") != -1) 
      {
           var parts = monthString.split("/");
           var year = parseInt(parts[1]);
           var month = parseInt(parts[0]);
           if(month == 0 || month > 12 || isNaN(month) || isNaN(year)) 
           {
               monthStr = '';
           }
           else
           {
               monthStr = month > 9 ? '' + month : '0' + month ;
               monthStr+= '/' + year;
           }
      }
      return monthStr; 
  }
  
  changeSiteValue(filterExpr: any){
      console.log('inside on pophelp onFiler==>',filterExpr);
          this.changeSingleValues(filterExpr);

  }
}
