import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { DatePipe } from '@angular/common';

import { DashboardFilterComponent } from '../dashboard-filter.component';
import { FilterDataService } from '../filter-data.service';
import { FilterInfo } from '../filter-input/filter-info.model';

@Component({
  selector: 'filter-screen',
  templateUrl: './filter-screen.component.html',
  styleUrls: ['./filter-screen.component.css'],
  providers:[DatePipe]
})
export class FilterScreenComponent implements OnInit {

    @Input('deviceType') deviceType: string = 'browser'; // browser,mobile
    @Input('dateFormat') dateFormat: string = 'dd-MM-yy';
    @Input('metadataName') metadataName: string | any; //Dashboard metadataName
    
    filters: any[] = [];
    filterDisplay : string = 'N';
    fromDateInput : Date | any =null;
    toDateInput : Date | any =null;
    dueDate: any;
    inValid:boolean | any;

    filterExprInput: any = {};

    submittedData: FilterInfo[] = [];

    constructor(public dashboardFilterComponent: DashboardFilterComponent, public filterDataSvc: FilterDataService, public datePipe:DatePipe) { }

    onSubmit(event: any) {
        console.log('Hi Vicky onSumbit called from bb-criteria',event);
        this.submittedData = event;
        this.applyFilter(event);
        this.dashboardFilterComponent.onFilterDone(this.submittedData);
    }

    ngOnInit() 
    {
         this.dashboardFilterComponent.init();
         console.log( 'FilterScreenComponent ngOnInit-----metadataName[',this.metadataName,']deviceType[',this.deviceType,']dateFormat[',this.dateFormat,']' );
         this.filterDataSvc.setFilters(this.metadataName);
         this.filterDisplay = this.filterDataSvc.filterDisplay;
         this.filters = this.filterDataSvc.getFilters();
         console.log( 'ngOnInit-----filters[', this.filters,'] filterDisplay[', this.filterDisplay, ']' );
    }

	//Added by Samruddhi on 22-Sept-2021 to set criteria pop up window height in Dashboard [Start]
    ngAfterViewInit()
    {
        let bbFilterElem = document.getElementById('bb-filter-container');
        if(bbFilterElem != null)
        {
            bbFilterElem.setAttribute('style', 'height: 62vh !important;');
        }
    }
    //Added by Samruddhi on 22-Sept-2021 to set criteria pop up window height in Dashboard[End]

    updateFilterParam(filterInfo: any) 
    {
/*        if(filterInfo.mandatory == 'Y' && filterInfo.changedValue == null){
            this.isNotValid = this.isNotValid || true;
            console.log('fitler type  :',this.isNotValid);    
        }else {
            this.isNotValid = false;
        }*/
        
        console.log('updateFilterParam filterInfo :', this.submittedData.length, filterInfo);
        if(filterInfo.col_name=='fromDate'){
            this.fromDateInput=filterInfo.changedValue;
           
            this.fromDateInput=this.toDate(this.fromDateInput);
        }

        if(filterInfo.col_name=='toDate'){
            this.toDateInput=filterInfo.changedValue;
           
            this.toDateInput=this.toDate(this.toDateInput);
        }

        var index = this.submittedData.findIndex( function(elm) {
            return filterInfo.col_name == elm.col_name;
        });
        console.log('updateFilterParam index filterInfo :',index);
        if( index == -1)
        {
            this.submittedData.push(filterInfo);
            console.log('submittedData in if of filterSCreen',this.submittedData);
        }
        else
        {
            this.submittedData[index] = filterInfo;
            console.log('submittedData in else of filterSCreen',this.submittedData);
        }
        console.log('updateFilterParam submittedData.length :', this.submittedData.length);
        console.log('updateFilterParam fromDate :', this.fromDateInput,this.toDateInput);
        
     
    }
    
    //Added Kamal.P to get filterExpression value  from filterInput component START
    onPophelp(filterExpr: any){
        var filterExprFieldName = filterExpr.substring(filterExpr.indexOf(':')+1, filterExpr.lastIndexOf(':'));
        console.log('inside on pophelp filterExpressionValue==>',filterExprFieldName);
        
        this.submittedData.forEach(
            filterInfo => {
                console.log(' inside if condition on popHelp filterInfo value when data is submited==>',filterInfo);
                if(filterInfo.col_name == filterExprFieldName){
                    this.filterExprInput[filterExprFieldName] = filterInfo.changedValue;
                    console.log('filterExpObj value inside on popHelp==>',this.filterExprInput);
                }
            }
        );
    }
    //Added Kamal.P to get filterExpression value  from filterInput component END

    toDate( dateStr: any ) 
    {
        console.log('fromDate::::::::',dateStr);
        
        if(dateStr.indexOf('/') != -1)
        {            
            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" );
            this.dueDate= datePipe.transform(dateStr, 'dd/MM/yyyy' );
            console.log('dueDate::: :',this.dueDate);
            var parts = this.dueDate.split( "/" );
            console.log('parts::: :', parts);
            return new Date( parts[2], parts[1]-1,parts[0]  );            
        }
        else
        {
            return new Date( dateStr  );
        }    
        
        
    }

    submit(){
        console.log('form values',this.submittedData);
    }
  
    closeFilter(event: any)
    {
        console.log('closeFilter...');
        this.filterDataSvc.clearFilterParameters();
        this.dashboardFilterComponent.onFilterDone(event);
    }

    applyFilter(event: any) 
    {
       var  count=1;

        console.log('submittedData :',this.submittedData);
        for(var filter of this.submittedData){
            console.log('filter ',filter);
            console.log('filter.changedValue ',filter.changedValue);
            
            if(filter.mandatory =='Y' && ( filter.changedValue==null ||  filter.changedValue==""))
            {
              count++;
              console.log('Inside filter mandatory count if',count);
                
            }
        }
        console.log('OUTER count',count);
        if(count<=1)
        {            
            var filterParams = '';
            console.log('submittedData :',this.submittedData);
            for(var filter of this.submittedData )
            {
                filterParams += filter.col_name + "=" + filter.changedValue + "&";

            }
            console.log('applyFilter filterParams',filterParams);
            
            this.filterDataSvc.setFilterParameters(this.metadataName, filterParams, this.submittedData);

            this.dashboardFilterComponent.onFilterDone(this.submittedData);
        }
        else
        {
            this.inValid=true;
            alert('Please fill mandatory field');
            console.log('unAuthorized :',count);
        }

    }
    
}
