import { Component, OnInit,Input, Output, EventEmitter, NgZone } from '@angular/core';
import { BBCustomChartComponent } from "src/components/dashboard/dashboard-composite/custom/bb-custom-chart/bb-custom-chart.component";
import { ViewChild } from "@angular/core";
import { ViewEncapsulation } from "@angular/core";

@Component({
  selector: 'bb-custom-series-chart-panel',
  templateUrl: './bb-custom-series-chart-panel.html',
  styleUrls: ['./bb-custom-series-chart-panel.css'],
  encapsulation: ViewEncapsulation.None
})
export class BBCustomSeriesChartPanel implements OnInit {

  constructor( private zone : NgZone ) { }
  @Input() chartDataSource : any;
 
  @Input() chartDetailModel : any;
   @Input() bgColorArr : any;
   @Output() onDrillDown: EventEmitter<any> = new EventEmitter(); //Added by Pramod S on 16-APR-21 for click on bar chart [START]

  headerTitle: any;
  imageSrc: any;
 
  chartCount: any;
  bgColorCSS:boolean = false;

  tabContentInitials: any = 'NA';
  visitCalls: any;
  textColor2 = "";//added by sainath for ang9 , bacause it is used in template but not declared
  ngOnInit()
  {
    console.log('ngOnInit :: chartConfig >', this.chartDataSource, 'chartDetailModel >>', this.chartDetailModel);
      var visitCallsColumn = this.chartDetailModel['visitCallsColumn'];   
      this.visitCalls = this.chartDataSource[visitCallsColumn];
      console.log('VISIT_CALLS_INFO >', this.visitCalls);
      var titleColumn = this.chartDetailModel['title_column'];   //console.log('titleColumn >', titleColumn);
      var imageColumn = this.chartDetailModel['image_column'];    //console.log('imageColumn >', imageColumn);
      this.headerTitle = this.chartDataSource[titleColumn];   console.log('headerTitle >>', this.headerTitle);
      var image = this.chartDataSource[imageColumn];     console.log('image >>', image);

      if( this.headerTitle ) {
        var initials = this.headerTitle.match(/\b\w/g) || [];
        this.tabContentInitials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
      }

      if( image ) {
        this.imageSrc = ( image.indexOf('/') == -1 ) ? 'dashboard/assets/images/svg/'+ image : image;
      }

      console.log('imageSrc  >>', this.imageSrc);

      console.log('tabContentInitials  >>', this.tabContentInitials);
        
      console.log('this.chartDataSource[CHART_INFO] >>', this.chartDataSource['CHART_INFO'] );

      var chartDetailModel_ = this.DEEP_CLONE( this.chartDetailModel );
      var chartDataSource_ =  this.DEEP_CLONE( this.chartDataSource );

      this.bgColorCSS = this.chartDataSource['customCss'];  
      console.log('bgColorCSS >>>', this.bgColorCSS);
         console.log(this.bgColorCSS == true);

      console.log('chartCount >>>', this.chartCount);

      this.multipleChartsDataArr__ = this.configureCharts(chartDetailModel_ , chartDataSource_);

      console.log('ngOnInit :: chartConfig #3 >', chartDataSource_, 'chartDetailModel >>', chartDetailModel_);

  }

  ngAfterViewInit() {
      try {
            console.log('ngAfterViewInit');

            console.log('ngAfterViewInit ::multipleChartsDataArr :: ', this.multipleChartsDataArr);
            console.log(this.multipleChartsDataArr.length);
            
            var bullets = document.getElementsByClassName('bullet_2');
            console.log('bullets >>', bullets);
            console.log(bullets.length);

            console.log('multipleChartsDataArr__ >>', this.multipleChartsDataArr__);

            //var bgColorArr = [];

            if ( bullets ) {
                for ( var i = 0; i < bullets.length; i++ ) {
                    console.log('bullets [i] >>', bullets[i]);
                    bullets[i].setAttribute('style','background:' + this.bgColorArr[i] + '!important;');
                    console.log('bgColorArr :: ngAfterViewInit >>', this.bgColorArr);
                }

            }
             console.log('bullets #2>>', bullets);


            //bullet_2
            /*

            if ( charts ) {
                for ( var i = 0; i < charts.length; i++ ) {
                    console.log('charts [i]', charts[i]);

                    var chartWidth = 100 / this.chartCount;
                    console.log('chartWidth >>', chartWidth);

                    charts[i].setAttribute('style','width:' + chartWidth + '%;');
                }
            }
            */
            //console.log('bulletsColorArr #2 ::', this.bulletsColorArr);       
      }
      catch(e) {
          console.log('exception e==>', e);
      }
  }

  multipleChartsDataArr: any = [];
  multipleChartsDataArr__: any[] = [];
  configureCharts( chartDetailModel_: any , chartDataSource_: any )  {
        console.log('ngOnInit :: chartConfig >', chartDataSource_, 'chartDetailModel >>', chartDetailModel_);
        var chartDataSource = this.DEEP_CLONE( chartDataSource_ );
        var chartDetailModel = this.DEEP_CLONE( chartDetailModel_ );
        console.log('configureCharts :: chartDataSource >>', chartDataSource);
        console.log( 'this.chartDetailModel >>',  chartDetailModel);

        var chartsConfig = chartDetailModel['chartConfig'];        

        for( var j = 0; j < chartsConfig.length; j++ ) {
            console.log('chartsConfig [j] >', chartsConfig[j]);

            if ( chartsConfig[j]['chartType'] == 'doughnut' ) {
                var chartDatasets = this.configureDoughnutCharts( chartsConfig[j] , chartDataSource );
                // this.multipleChartsDataArr.push(chartDatasets);
                this.multipleChartsDataArr.push(chartDatasets);
            }
            else if ( chartsConfig[j]['chartType'] == 'horizontalBar' ) {
                console.log('not doughnut ', chartsConfig[j]['chartType']);             
                var chartDatasets = this.configureHorizontalBarCharts( chartsConfig[j] , chartDataSource );
                console.log('chartDatasets #### >>', chartDatasets);
                // this.multipleChartsDataArr.push(chartDatasets);
            }
        }

        console.log('multipleChartsDataArr >>', this.multipleChartsDataArr);

        return this.multipleChartsDataArr;
  }

maxDataLimitArr: any;

  configureHorizontalBarCharts ( chartConfig: any, chartDataSource: any ) 
  {
        var _chartConfig = this.DEEP_CLONE( chartConfig );
        var _chartDataSource = chartDataSource['CHART_INFO'];
        console.log('_chartDataSource @@@$$$ >>', _chartDataSource );


        var chartType = _chartConfig['chartType'];
        var chartScales = _chartConfig['chartScales'];
       
       /* var chartDatasets = _chartConfig['datasets'];
        console.log('chartDatasets @@@@@ >>>', chartDatasets);*/

        var _datasets = chartDatasets  || [];
        var options = _chartConfig['options'];
        var title=chartDataSource['TITLE']; //Added by Pramod S on 16-APR-21 for click on bar chart [START]
        console.log('configureHorizontalBarCharts :: options #1 :: ', options);

        var processedDatasets_: any =[];
        var chartData_ = [];

        var _dataset = {};
        var _data_ = {};

        var processedDataArr = [];
        var peocessedLabelsArr = [];
        var bgColorData;
        //Added by Pramod S on 16-APR-21 for click on bar chart [START]
        var onClick =options['onClick'];

        if(!options.onClick)
        {
            console.log("in !Options ",options);
            options.onClick = (event: any, active: Array<any>) => {
                console.log("onclick1[",event,"]");
            }; 
        }
        if(options.onClick)
        {
            var self =this;
            options.onClick = (event: any, active: Array<any>) => {
                console.log("title ::",title);
                console.log(active[0]);
                
                if(active.length >0)
                {
                    var label=active[0]._view.label;
                    console.log("Label::[",label,"]");
                    var link;
                    if(label == "Not Visited")
                    {
                       link="not_visited" 
                    }
                    else 
                    {
                        link="visited"
                    }
                    var obj=
                    {
                        "LINK_METADATA":link,
                        "VISIT_TITLE":label,
                        "TITLE":title
                    };
                    console.log(":: obj",obj);
                    console.log("Titl :::",title);
                    this.onDrillDown.emit(obj);
                }
            };
            console.log("in onclick work--");
        }
        //Added by Pramod S on 16-APR-21 for click on bar chart [END]

        for ( var i = 0; i < _chartDataSource.length; i++ ) {
            console.log('_chartDataSource ^^^^###$$$ >>', _chartDataSource[i] );
            if( _chartDataSource[i]['CHART_TYPE'] == chartType ) {
                chartData_ = _chartDataSource[i]['CHART_INFO'];
                bgColorData = _chartDataSource[i]['backgroundColor'];
                console.log('bgColorData >>>', bgColorData);
                console.log(typeof(bgColorData));

                if(typeof(bgColorData) === 'string' ) {
                bgColorData = JSON.parse(bgColorData);
                }
                console.log('bgColorData #2>>>', bgColorData);
                console.log(typeof(bgColorData));
                }
        }

        console.log('configureHorizontalBarCharts :: chartType >>', chartType, '_chartConfig >>', _chartConfig, 'chartData_ >>', chartData_);

        var chartDatasets = _chartConfig['datasets'];
        console.log('chartDatasets @@@@ #2 >>>', chartDatasets);
        var backgroundColorArr: any = bgColorData;
        console.log('backgroundColorArr >>>', backgroundColorArr);

        if ( chartData_.length > 0 ) {
            for( var i = 0; i < chartDatasets.length; i++ )  {
                    console.log('chartDatasets >>>>', chartDatasets);
                    console.log('chartDatasets[i] >>>>', chartDatasets[i]);
                    console.log('chartDatasets[0] >>>>', chartDatasets[0]);

                    var dataColumn = chartDatasets[0]['y_column'];
                    console.log('dataColumn ## >>>>', dataColumn);

                    var labelColumn = chartDatasets[0]['x_column'];
                    console.log('labelColumn ## >>>>', labelColumn);

                    var chartTextColumn = chartDatasets[0]['chartText'];
                    console.log('chartTextColumn >>>>>>', chartTextColumn );

                    var titleColumn = chartDatasets[0]['ttt_column']; // ToolTipTitle
                    var legendsColumnDescr = chartDatasets[0]['y_column_descr'];
                    console.log('legendsColumnDescr ## >>>>', legendsColumnDescr);

                    console.log('chartData_ >>>', chartData_);
                    // var dataArr = chartData_.map((_chartData => {
                    //         return _chartData[dataColumn];
                    // }) );
                    var dataArr = chartData_.map((_chartData: any) => {
                        return _chartData[dataColumn];
                    } );

                    // var labelsArr = chartData_.map((_chartData => {
                    //         return _chartData[labelColumn];
                    // }) );
                    var labelsArr = chartData_.map((_chartData: any) => {
                        return _chartData[labelColumn];
                    } );

                    // var chartTextArr = chartData_.map((_chartData => {
                    //         return _chartData[chartTextColumn];
                    // }) );
                    var chartTextArr = chartData_.map((_chartData: any) => {
                        return _chartData[chartTextColumn];
                    } );

                    console.log('chartTextArr >>>', chartTextArr);
                    console.log(typeof(chartTextArr));
                    console.log('dataArr >>', dataArr);
                    if(typeof(dataArr) === 'string' ) {
                        dataArr = JSON.parse(dataArr);
                    }

                    console.log('labelsArr >>', labelsArr);
                    if(typeof(labelsArr) === 'string' ) {
                        labelsArr = JSON.parse(labelsArr);
                    }
                    _chartConfig['labels'] = labelsArr;

                    var dataColumnDescr = legendsColumnDescr;
                    console.log('dataColumnDescr >>', dataColumnDescr);


                    var bgColorsArr: any =[];
                    var backgroundColor;
                    for( var k = 0; k < chartTextArr.length; k++ )
                    {
                        console.log('backgroundColorArr[k] >>', backgroundColorArr[k]);
                        bgColorsArr.push(backgroundColorArr[k]);
                    }

                    backgroundColor = bgColorsArr;

                    //dataArr = chartTextArr;
                    var _dataArr: any = [];
                    if( chartTextArr.length > 1 ) {
                        for( var a = 0; a < chartTextArr.length; a ++ ) {
                            console.log('chartTextArr[a] == ', chartTextArr[a]);
                            _dataArr.push(chartTextArr[a]);
                        }
                    }
                    else{
                        _dataArr = chartTextArr;
                    }

                    console.log('_dataArr  >> ', _dataArr );
                    var limitArr = [];
                    limitArr = _dataArr;

                    this.maxDataLimitArr = Math.max(...limitArr);
                    
                    _dataset = {
                        'chartTextArr' : chartTextArr,
                        //'data' : _data_,
                        'data' :  _dataArr, 
                        'labels' : labelsArr,
                        'titles' : dataColumnDescr,
                        'dataSource' : '',
                        'label': 'Dr Count',
                        'backgroundColor': backgroundColor
                    };
                    console.log( '_dataset', _dataset);
                    processedDatasets_.push( _dataset );              

            }
            _chartConfig['datasets'] = processedDatasets_;
            console.log('processedDatasets_ !!!!!!!!', processedDatasets_);

        }

        var _displayTopBar = options['displayTopBar'];
        
        if (  _displayTopBar == true ) {
            console.log('#############');
            if( _chartConfig['chartText'] ) {
                console.log('$$$$$$$$$$$$$$');
                if( chartData_  && chartData_.length > 0 ) {
                    var chartTextStr ;
                    if( chartData_[0] ) {
                        chartTextStr = chartData_[0][_chartConfig['chartText']];
                    }
                    console.log('chartTextStr $$$>>', chartTextStr);
                    console.log(typeof(chartTextStr));
                    var fontFamily = '';

                    if( this.bgColorCSS == true ) {
                        fontFamily = "Arial, Helvetica, sans-serif";
                    }
                    else {
                        fontFamily = "Roboto, sans-serif";
                    }

                    var chartText = { 
                        "text" : chartTextStr,
                        "fontSize" : 12,
                        "padding" : 1,
                        "fontFamily" : fontFamily
                    };
                    console.log('chartText %%% >>', chartText);

                    options['chartText'] = chartText;
                }
            }
        }

        /*
        console.log('_chartConfig  &&&&&&& >>', _chartConfig);
        console.log('chartData_  &&&&&&&& >>', chartData_);

        */
        if( chartData_ && chartData_.length > 0 ) {
            var chartScales = _chartConfig['chartScales'];
            console.log('chartScales >>>', chartScales);
            console.log('maxDataLimitArr ::: P', this.maxDataLimitArr);

            if( chartScales ) {                
                chartScales['xAxes'][0]['ticks']['max'] = this.maxDataLimitArr + ( this.maxDataLimitArr / 2 );               
            }

            if(chartScales) {
                // Add ScaleLabel in options - Starts
                var xColumnLbl = options['x_column_label'];
                if( xColumnLbl )
                {
                    var xAxis = chartScales.xAxes[0];
                    var scaleLabel: any = {};
                    if( xAxis['scaleLabel'] )
                    {
                        scaleLabel = xAxis['scaleLabel'];
                        if( scaleLabel['display'] )
                        {
                            scaleLabel['labelString'] = xColumnLbl;
                        }
                    }
                    else
                    {
                        scaleLabel['display'] = true;
                        scaleLabel['labelString'] = xColumnLbl;
                    }

                    xAxis['scaleLabel'] = scaleLabel;
                }

                var yColumnLbl = options['y_column_label'];
                if( yColumnLbl )
                {
                    var yAxis = chartScales.yAxes[0];
                    var scaleLabel: any = {};
                    if( yAxis['scaleLabel'] )
                    {
                        scaleLabel = yAxis['scaleLabel'];
                        
                        if( scaleLabel['display'] )
                        {             
                            scaleLabel['labelString'] = yColumnLbl;
                        }
                    }
                    else
                    {
                        scaleLabel['display'] = true;
                        scaleLabel['labelString'] = yColumnLbl;
                    }

                    yAxis['scaleLabel'] = scaleLabel;
                }
                console.log('scaleObject >>', chartScales);

                var ticks = chartScales['yAxes'][0]['ticks'];
                console.log('ticks #1>>', ticks); 

                var customCSS = chartDataSource['customCss'];
                console.log('customCSS **********', customCSS);

                if( customCSS == true ) {
                    var ticks = chartScales['yAxes'][0]['ticks'];
                    console.log('ticks >>', ticks);

                    chartScales['yAxes'][0]['ticks']['fontColor'] = 'white';    
                    options['topBarValueColor'] = 'white';
                }

                console.log('chartScales ^^^^^^^^ >>', chartScales);

                options['scales'] = chartScales;
            }
            console.log('configureHorizontalBarCharts :: _chartConfig !!@@@@ >>', _chartConfig);
    }

        return _chartConfig;
    }
 
    visitInfoColumn: any;
    drCountColumn: any;
    bulletsColor: any ;

    chartDataEmpty: boolean = false;
  configureDoughnutCharts( chartConfig: any, chartDataSource: any ) {

        console.log('configureDoughnutCharts :: doughnut chartConfig >>', chartConfig, 'chartDataSource >>', chartDataSource);

        var _chartConfig = chartConfig;
        var _chartDataSource = chartDataSource['CHART_INFO'];
        var bulletColor2 = chartDataSource['bulletColor2'];
        console.log('bulletColor2  &&&&&&&& >>', bulletColor2);
        console.log(typeof(bulletColor2));

        var chartType = _chartConfig['chartType'];
        var chartDatasets = _chartConfig['datasets'];
        var options = _chartConfig['options'];
        var chartData_: any = {};
        if( _chartDataSource && _chartDataSource.length > 0 ) {
            for ( var i = 0; i < _chartDataSource.length; i++ ) {
                if( _chartDataSource[i]['CHART_TYPE'] == chartType ) {
                    chartData_ = _chartDataSource[i]['CHART_INFO'][0];
                    this.bulletsColor = _chartDataSource[i]['bgColorClass'];
                }
            }
        }
        console.log('bulletsColor :: ', this.bulletsColor);
        console.log('configureDoughnutCharts :: chartData_ >>>', chartData_);

        if ( chartData_ && ( JSON.stringify(chartData_) != JSON.stringify({}) ) ) {
            this.chartDataEmpty = false;
        }
        else {
            this.chartDataEmpty = true;
        }
        console.log('chartDataEmpty >>', this.chartDataEmpty);




        if ( chartData_ && ( JSON.stringify(chartData_) != JSON.stringify({}) ) ) {
            console.log('********************************************');

            this.visitInfoColumn = chartData_['ACTUAL_VISITS'] ;
            this.drCountColumn = chartData_['NO_DOCTORS'];
            var processedDatasets: any =[];
            var _dataset = {};
            for( var i = 0; i < chartDatasets.length; i++ ){
                if ( chartDatasets[i]['data'] ) {
                    
                    var dataArray: any=[];
                    var dataColumn = chartDatasets[i]['data'];
                    for( var k = 0; k < dataColumn.length; k++ ) {
                        dataArray.push(chartData_[dataColumn[k]]);
                    }   

                    var labelsArray: any =[];
                    var bgColorColumn = chartDatasets[i]['backgroundColor'];
                    var bgColorArray=[];

                    bgColorArray = chartData_[bgColorColumn];        
                    
                    var newDataArray: any =[];

                    if ( dataArray.length == 2 ) {
                        for ( var l = 0; l < dataArray.length; l++ ) {
                            if ( l == 0 ) {
                                newDataArray.push(dataArray[0]);
                            }
                            else if ( l == 1 ) {                            
                                var val = dataArray[1] - dataArray[0];
                                newDataArray.push( val );
                            }
                        }
                    }
                    else {
                        newDataArray = dataArray;
                    }   

                    _dataset = {
                        'data' : newDataArray,
                        'labels' : labelsArray,
                    // 'titles' : titlesArr,
                        'backgroundColor' : bgColorArray,
                    // 'label': dataColumnDescr
                        //'bgColorClass': bgColorClass
                        'bulletsColor': this.bulletsColor
                    };
                    console.log( '_dataset', _dataset); 
                    processedDatasets.push( _dataset );                 
                }
                _chartConfig['datasets'] = processedDatasets;
            }
            
            var chartCenterTextColor  = "black";
            var chartCenterTextFont = "14px  Roboto,sans-serif";
            var chartCenterTextColor2 = "gray"; 
            var chartCenterText = ' ';
            var chartCenterTextFont2 ="12px  Roboto,sans-serif";
            
            if ( _chartConfig && _chartConfig['chart_center_text'] ) {
                var chartCenterTextColumn = _chartConfig['chart_center_text'];


                var customCSS = chartDataSource['customCss'];
                console.log('customCSS ^&&&&&', customCSS);

                if ( customCSS == true) {
                    chartCenterTextColor = "white";
                    chartCenterTextColor2 = "white";
                    chartCenterTextFont = "bold 18px  Arial, Helvetica, sans-serif ";
                    chartCenterTextFont2 = "14px  Arial, Helvetica, sans-serif ";
                    console.log('chartCenterTextColor >>', chartCenterTextColor);
                }
                else{
                    chartCenterTextColor = "black";
                    chartCenterTextColor2 = "gray";
                    chartCenterTextFont = "bold 18px  Roboto,sans-serif";
                    chartCenterTextFont2 = "14px  Roboto,sans-serif";
                    console.log('chartCenterTextColor #2>>', chartCenterTextColor);              
                }

                if( chartCenterTextColumn ) {
                    if( chartData_ ) {
                        var chartCenterTextArr = chartData_[chartCenterTextColumn];
                        if(typeof(chartCenterTextArr) === 'string' ) {
                            chartCenterTextArr = JSON.parse(chartCenterTextArr);
                        }
                        console.log('chartCenterTextArr >>', chartCenterTextArr);
                        for ( var i = 0; i < chartCenterTextArr.length; i++ ) {
                            chartCenterText = chartCenterTextArr[i];
                            var labelIndex; var labelIndex1; 
                            var text1 = ''; var text2 ='';
                            labelIndex = chartCenterText.indexOf('Plan Visit');
                            labelIndex1 = chartCenterText.indexOf('Drs');

                            if( labelIndex > 0 ){
                                text1 = chartCenterText.substring(0, labelIndex);
                                text2 = chartCenterText.substring(labelIndex, chartCenterText.length);
                            }

                            if( labelIndex1 > 0 ){
                                text1 = chartCenterText.substring(0, labelIndex1);
                                text2 = chartCenterText.substring(labelIndex1, chartCenterText.length);
                            }

                            if(  i > 1 ) {
                                //TODO 
                                //return; 
                                break;
                            }
                            if ( i == 0 ) {
                                options['chartCenterText'] = text1;
                                options['chartCenterTextColor1'] = chartCenterTextColor;
                                options['chartCenterTextFont1'] = chartCenterTextFont;
                                options['chartCenterText2'] = text2;
                                options['chartCenterTextColor2'] = chartCenterTextColor2;
                                options['chartCenterTextFont2'] = chartCenterTextFont2;
                            }
                            else {
                                options['chartCenterText3'] = text1;
                                options['chartCenterTextColor3'] = chartCenterTextColor;
                                options['chartCenterTextFont3'] = chartCenterTextFont;
                                options['chartCenterText4'] = text2;
                                options['chartCenterTextColor4'] = chartCenterTextColor2;
                                options['chartCenterTextFont4'] = chartCenterTextFont2;                   
                            }
                        }
                    }
                }
            }
            _chartConfig['options'] = options;
            console.log('_chartConfig >>', _chartConfig );

        }

    return _chartConfig;
  }

  DEEP_CLONE( data: any )
  {
      try
      {
          var clonedData = JSON.parse(JSON.stringify(data));
          return clonedData
      }
      catch(e)
      {
          return data;
      }
  }

  imageNotFound = false;

  setImageNotFound( imagePresent: any ) {
      console.log( 'imagePresent >>', imagePresent);
      this.imageNotFound = true;

  }

}
