import { Component, OnInit , Input , ViewEncapsulation , ViewChild} from '@angular/core';
//import { Chart } from 'chart.js';
//import { BBChartDirective } from './bb-chart.directive';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ChartService } from './chart.service';
import { GROUP_BY } from '../../plugin/utils/dashboard-plugin-util';


@Component({
  selector: 'chart-component',
  templateUrl: './chart-component.component.html',
  styleUrls: ['./chart-component.component.css'],
  host: { '[style.height]': 'chartContHeight' },
  encapsulation : ViewEncapsulation.None
})
export class ChartComponentComponent implements  OnInit {
  //@Input() data;
  //@Input() labels;
    @Input('data') reportData : any;
    @Input() chartProperties: any;
    @Input() type: any;
    @Input() metadata: any;
    @Input('elWidth') elWidth: any;
    @Input('dataArrayInput') dataArrayInput: any;
    
    borderColor = 'white';
    borderWidth  = 2;
    animateScale:boolean = true ;
    animateRotate:boolean = false ;
    
    labels: any = [];
    dataArray: any = [];
    strMetadata:any;
    chartHeight: any = '330px';
    chartWidth = '300px';
    cutOutPercentage = 70;
    chartContHeight = '400px';
    contHeight = 'auto';
    
    chartType:string = "doughnut";
    legend:boolean = false;
    customLabels:boolean = true;
    customLegend:boolean = true;
    chart: any;
    displayText: any;
    paddingleft: any;
    paddingRight: any;
    colmnGroupId: any[] =[];
    displayTextValue='';
    legendPosition: any;
    isNullData = true;
    dataArrayCount: any;
    colors:Array<number[]> = [];
    colorsList: any = {};
    isTodaysCallDb: any;
    finalResult: any;
    result: any;
    groupData: any;
    opacity=0.6;
    dataKey: any;
    valueKey: any;
    backgroundColor: any;
    
	//To set Chart Canvas Height and Width 
    barChartCanvasWidth = 480;
    barChartCanvasHeight = 300;
    
    public barChartType:string = 'horizontalBar';
    
      public barChartLabels:string[] = [];
      public barChartData:any[] = [];

    displayTopBar:boolean = true;
    data: any[]=[]; 
    labelData: any[]=[];    
    public barChartOptions:any = {
            scaleShowVerticalLines: true,
            responsive: true,
          
            //Number - Pixel width of the bar
            //barWidth: 0.2,
            scales: {
                  yAxes: [{
                    //  barPercentage: 0.5,  //use to maintain thickness of bar  from range  0  to 1.0
                    //   barThickness : 30,  // increase width of basr
                        ticks: {
                           fontColor: "black",
                           fontStyle: "500",
                           fontSize: 12,
                        },
                        scaleLabel: {
                           display: true
                        }
                   }],
                  xAxes: [{
                        ticks: {
                          min: 0,
                          stepSize: 25,
                          max: 100,
                          fontColor: "black",
                          fontSize: 12,
                          fontStyle: "500",
                        },
                        scaleLabel: {
                          display: true
                        },
                        gridLines: {
                          display:true,  // To display gridLines 
                        }
                  }]
                }
          };
    
    
    
    public constructor( private _sanitizer:DomSanitizer  , private chartService:ChartService) { }
    
    public doughnutChartOptions:any = {
        animation: 
        {
            animateScale: true,
        },
        responsive: true ,
        maintainAspectRatio: false
    };
    
    ngOnInit()
    {
        console.log("reportData in chart-component ==  > " , this.reportData , this.reportData.metadataname,this.dataArrayInput  );
        
        if(this.reportData.chart_properties && this.reportData.chart_properties.label && this.reportData.chart_properties.opacity!='NAN' ){
            this.displayTextValue=this.reportData.chart_properties.label;
        }
        
        if(this.reportData.chart_properties && this.reportData.chart_properties.cutOutPercentage  ){
            this.cutOutPercentage=this.reportData.chart_properties.cutOutPercentage;
        }
        console.log('cutOutPercentage ::::::::',this.cutOutPercentage);

        if(this.reportData.chart_properties  && this.reportData.chart_properties.opacity && this.reportData.chart_properties.opacity!='NAN'){
            this.opacity=this.reportData.chart_properties.opacity;
        }
        this.dataArrayInput = this.dataArrayInput || this.reportData.chart_properties.dataArrayInput;
        console.log('opasity ',this.opacity);
        
        if(this.reportData.data){
            this.result = this.reportData.data;
            try
            {
                this.result = JSON.parse(this.reportData.data);
            }
            catch(e)
            {
                this.result = this.reportData.data;
            }
            
            if(this.dataArrayInput){
                console.log('data input array ',this.result[this.dataArrayInput]);
                this.result= this.result[this.dataArrayInput];
                console.log('data input array ',this.result);
                if(this.dataArrayInput == 'TODAYS_SUMMARY'){
                    this.isTodaysCallDb = true;
                }
            }
       }
        
        if(this.reportData.chart_properties){
            console.log('report data ', this.reportData.chart_properties);
           this.chartHeight = this.reportData.chart_properties.height ;
            this.chartWidth = this.reportData.chart_properties.width;
            this.chartType = this.reportData.chart_properties.chart_type.value;
            this.legendPosition = this.reportData.chart_properties.legendPosition;
            this.backgroundColor = this.reportData.chart_properties.backgroundColor;
            this.dataArrayInput = this.dataArrayInput || this.reportData.chart_properties.dataArrayInput;

            var colorsList = this.reportData.chart_properties.colors;
            if(colorsList && colorsList.key && colorsList.value){
                var key = colorsList.key;
                var value = colorsList.value;
            }
            if(this.chartHeight && this.legendPosition == 'inline'){
                var height = this.chartHeight.match(/\d+/g).map(Number)[0];
                //this.chartContHeight = height + 50 + 'px';
                this.chartContHeight = 'auto';
                this.contHeight = 'inherit';
            }
            
            if(colorsList && colorsList.color){
                console.log('inside color list ');
                colorsList.color.forEach(
                        (colorVal: any) => {
                            if(colorVal){
                                //this.colors.push(colorVal.value.split(','));
                                var id;
                                if(key){
                                    console.log('key::::::',key,value,this.result);
                                    var res;
                                    if(this.result && Array.isArray(this.result)){                                        
                                        res = this.result.find( rs => rs[key] == colorVal.id );
                                    }                                    

                                    console.log('res::::::',res);
                                    if(res){
                                        id = res[value];
                                        this.colorsList[id] = colorVal.value.split(',');
                                    }
                                    console.log('id::::::',id);
                                }else {
                                    id = colorVal.id;
                                    this.colorsList[id] = colorVal.value.split(',');
                                }
                            }
                        } 
                );
            }
            else
            {
                this.isTodaysCallDb = true; 
            }
            console.log('colorsList ::',this.colorsList);
        }
        if(this.reportData.data){
            this.processData();
            if(this.dataKey  || this.valueKey){
              var count=0;
              for(var  data of this.result)
              {
                this.dataArray.push(data[this.valueKey]);
                this.labels.push(data[this.dataKey]);
                count=count+data[this.valueKey];
                if(this.displayTextValue){
                    this.displayText=count;                    
                }
                console.log('display text ',this.displayText);
                if(this.colorsList){
                    console.log('inside pie chart color 1');
                    var color = this.colorsList[data[this.dataKey].trim()];
                    if(color){
                        this.colors.push(color);
                    }
                } 
                if(this.type=='H_BAR'){
                    console.log('inside Horizontal graph if',this.labels,this.dataArray,this.displayTextValue,this.backgroundColor);
                    this.barChartLabels=this.labels ;
                    this.barChartData= [
                     {data: this.dataArray, label: this.displayTextValue , labels : this.labels ,backgroundColor: this.backgroundColor}
                     ];
                    //To calculate Chart Canvas Height 
					if( this.barChartLabels )
                    {
                        var noOfBars = this.barChartLabels.length;
                        this.barChartCanvasHeight = noOfBars < 10 ? 300 : ( ( noOfBars * 30 ) + 100 );
                    }
                }
              }
            }
            else
            {
                console.log("groupByData in chart-component ==  > " , this.groupData );
                for(var  data of this.groupData){
                        this.labels.push(data.key);
                        this.dataArray.push(data.count);
                        if(this.colorsList){
                            console.log('inside pie chart color 2');
                            var color = this.colorsList[data.key.trim()];
                            if(color){
                                this.colors.push(color);
                            }
                        } 
                        if(this.type=='H_BAR'){
                            console.log('inside Horizontal graph ',this.labels,this.dataArray,this.backgroundColor);
                            this.barChartLabels=this.labels ;
                            this.barChartData= [
                                {data: this.dataArray, label: this.displayTextValue , labels : this.labels ,backgroundColor: this.backgroundColor}
                             ];
                            //To calculate Chart Canvas Height
							if( this.barChartLabels )
                            {
                                var noOfBars = this.barChartLabels.length;
                                this.barChartCanvasHeight = noOfBars < 10 ? 400 : ( ( noOfBars * 30 ) + 100 );
                            }
                        }
                }
            }

            console.log("this.labels " , this.labels , "this.dataArray " , this.dataArray , "this.displayText ==>" , this.displayText);       
       
            this.dataArray.forEach(
                    (optVal: any) => {
                        if(optVal > 0){
                            this.isNullData = false;
                        }
                    }
            );
        
        }
        console.log('barChartCanvasHeight [',  this.barChartCanvasHeight, '] ' );
    }
    
    
    chartLoaded(chart: any){
        console.log("chartLoaded == > " , chart);
        this.chart = chart;
    }
    
 // events
    public chartClicked(e:any):void {
      console.log(e);
    }
   
    public chartHovered(e:any):void {
      console.log(e);
    }
    
    public ngOnChanges(): void {
        if(this.chartWidth){
            //var padding = "calc(("+ this.elWidth +"px - "+ this.chartWidth +") / 2)";
            //this.paddingleft = padding;
            //this.paddingRight = padding;
        }
        console.log('ElWidth ===>',this.elWidth);
    }
        
    processData()
    {
        console.log('chart data  getColumnData');
        var columnGroup=this.reportData.column_group;
        if(columnGroup[0] !=null)
        {
            for(var colGroup of columnGroup)
            {
               var columns=colGroup.columns;
               console.log('columns>>>> 1',columns);

               if( columns != null )
               {
                   if( columns instanceof Array )
                   {
                       for(var colms of columns)
                       {
                           console.log('columns in chart component::::',colms);
                           this.formatedData(colms);
                           console.log('after group by 10 in chart component 1',this.result);
                       }                  
                   }
                   else
                   {
                       console.log('inside else of chart component ::::',columns);
                       if(columns instanceof Array)
                       {
                           for(var colm1 of columns)
                           {
                               console.log('column colum ',colm1);
                               this.formatedData(colm1);
                               console.log('after group by 10 in chart component 2',this.result);  
                           }                          
                       }
                       else
                       {
                           this.formatedData(columns);
                           console.log('after group by 10 in chart component 3',this.result);
                       }

                   }    
               }
            }
         }
     }
    
    
    formatedData(colms: any){
        console.log('Inside formated data ',colms);
        var aggFunction=colms.aggFunction;
        var value=colms.value;
        var typeOfColumn=colms.type;

        
        if(aggFunction=='COUNT'){
            this.finalResult = [];
            this.result.forEach(
                    (res: any) => {
                        var data = this.finalResult.find( (rs: any) => rs[value] == res[value] );
                        if(!data){
                            this.finalResult.push(res); 
                        }
                    }
            );
            console.log('Inside count ',this.finalResult);
            this.dataArrayCount=GROUP_BY(this.finalResult,value);
            console.log('data array count ',this.dataArrayCount);
            this.displayText=this.dataArrayCount.length;

        }
        else if(aggFunction=='GROUP_BY'){
            
            if( !this.finalResult )
            {
                this.finalResult = [];
                this.result.forEach(
                        (res: any) => {
                            var data = this.finalResult.find( (rs: any) => rs[value] == res[value] );
                            if(!data){
                                this.finalResult.push(res); 
                            }
                        }
                );
            }
            console.log('Inside group by ',this.finalResult,value);
            this.groupData=GROUP_BY(this.finalResult,value);
            console.log('Inside group by ',this.groupData);
        }
        else{
            if(colms.key){
                this.dataKey=colms.value;
            }
            if(colms.value){
                this.valueKey=colms.value;
            }
        }
    }

}

