import { Component, OnInit } from '@angular/core';
import { Input ,Output,EventEmitter} from "@angular/core";
import { ViewEncapsulation } from "@angular/core";

@Component({
  selector: 'bb-custom-chart-panel',
  templateUrl: './bb-custom-chart-panel.component.html',
  styleUrls: ['./bb-custom-chart-panel.component.css']
})
export class BBCustomChartPanel implements OnInit {

  constructor()
  {
      this.chartPanelId = '_' + (document.getElementsByTagName('bb-custom-chart-panel').length + 1);
  }

  @Input() chartDataSource : any;
  @Input() chartConfig : any;
  @Input() chartDetailModel : any;
  @Input('parentData') chartParentData : any;
  @Output() onDrillDown: EventEmitter<any> = new EventEmitter(); //Added by Pramod S on 16-APR-21 for click on bar 
  
  isTableData = false;

  _chartData: any;
  chartData:any;//added by sainath for ang9, because chartdata is used in template but not declared
  chartHeaderTitle: any = '';
  chartContentTitle: any = '';
  chartContentInitials: any = 'NA';
  chartLegend: boolean = true;

  imageInitials: any;
  imageSrc: any;
  altImageSrc: any;
  imageNotFound = false;

  options = { };

  chartSummary: any;
  chartHeight = 191;
  chartCanvasHeight = 191;
  chartPanelId;
  //isSeriesChart = false;


  //Added by Sonam
  isDataChart : boolean = false;
  chartDataset: any[] = [];
  
  public datasets: any = [];
  chartColors : any = [];
  labelsArr :any = [];
  dataArr :any = [];
  chartType: any;
 
  //Added by SonamK
  formatSummaryValue : boolean = false;
  
  ngOnInit()
  {
     if( this.chartDetailModel )
	 {
          this.chartSummary = this.chartDetailModel['summary'];
        //this.isSeriesChart = this.chartDetailModel['series'];
        //this.isDataChart = this.chartDetailModel['dataChart']; 
    
        //Added by Sonam K
		  this.formatSummaryValue = this.chartDetailModel['formatValue'];
     }

     if( this.chartConfig['datasets'] ){

      	 this.chartConfig = this.processDataSets();
     }
     if ( this.chartConfig['chartType'] ) {
	     this.chartType = this.chartConfig['chartType'];
	     console.log('this.chartType   #',this.chartType);
	     if( this.chartType  == 'POLAR_AREA' )
	     {
	     	this.buildPolarAreaChartData();
	     }
	     else if(this.chartType  == 'CUSTOM_DOUGHNUT_CHART')
	     {
	     	this.buildCustomChartData();
         }
         //Added by Sonam K
         else if(this.chartType  == 'SERIES_CHART_PANEL')
	     {
	     	this.buildCustomChartData();
	     }
     }
     if ( this.chartConfig['colors'] ) {
 		this.chartColors = this.chartConfig['colors'];
     }
     this._chartData = this.DEEP_CLONE( this.chartDataSource );

      if( this.chartConfig )
      {
        this.applyConfiguration( this.chartConfig );
        /*
        var options = this.chartConfig['options'];
        if( options && options.height )
        {
            this.chartHeight = options.height; //Set Default height if not defined in Options
        }
        */
        this.setChartHeight();
      }
  }

  container: any;
  chartContainer: any =[];
  canvas: any =[];

  ngAfterViewInit() {
      try {
          var chartContentTempl = 'chartContentTempl' + this.chartPanelId;
          console.log('ngAfterViewInit',chartContentTempl, this.chartHeight , this.chartCanvasHeight );
          //this.container = document.getElementsByClassName('chartContentTempl');
          this.container = document.getElementsByClassName(chartContentTempl);

          for(var i = 0; i < this.container.length; i++) {
               this.chartContainer.push(this.container[i].getElementsByClassName('chart-container')[0]);
          }

          for( var i=0; i < this.chartContainer.length; i++) {
              this.chartContainer[i].setAttribute('style','width:100%;height:' + this.chartHeight + 'px;');
              this.canvas.push(this.chartContainer[i].getElementsByTagName('canvas'));
          }

          for(var i=0; i < this.canvas.length; i++) {
              //this.canvas[i][0].setAttribute('style','width:100%;height:' + this.chartHeight + 'px;');
              this.canvas[i][0].setAttribute('style','width:100%;height:' + this.chartCanvasHeight + 'px;');
          }
      }
      catch(e) {
          console.log('exception e==>', e);
      }
  }

  processDataSets( ) {
      var _chartConfig = this.chartConfig;
      var _chartDataSource = this.chartDataSource;
      var chartDatasets = this.chartConfig['datasets'];
      var options = this.chartConfig['options'];
      var _datasets = this.DEEP_CLONE( chartDatasets ) || [];
      var processedDatasets: any =[];
      var processedDataArr: any = [];
      var peocessedLabelsArr: any = [];

      for( var i = 0; i < chartDatasets.length; i++ )
      {
          var dataColumn = chartDatasets[i]['y_column'];
          var labelColumn = chartDatasets[i]['x_column'];
          var titleColumn = chartDatasets[i]['ttt_column']; // ToolTipTitle
        //   var dataArr = _chartDataSource.map((_chartData => {
        //       return _chartData[dataColumn];
        //   }) );
          var dataArr = _chartDataSource.map((_chartData: any) => {
            return _chartData[dataColumn];
            } );

          processedDataArr.push( dataArr );

        //   var labelsArr = _chartDataSource.map((_chartData => {
        //       return _chartData[labelColumn];
        //   }) );
          var labelsArr = _chartDataSource.map((_chartData: any) => {
            return _chartData[labelColumn];
        } );
          _chartConfig['labels'] = labelsArr;

          peocessedLabelsArr.push( labelsArr );

        //   var titlesArr = _chartDataSource.map((_chartData => {
        //       return _chartData[titleColumn];
        //   }) );
          var titlesArr = _chartDataSource.map((_chartData: any) => {
            return _chartData[titleColumn];
            } );

          var dataColumnDescr = chartDatasets[i]['y_column_descr'];
          var _dataset = {
            'data' : dataArr,
            'labels' : labelsArr,
            'titles' : titlesArr,
            'dataSource' : '',
            'label': dataColumnDescr
          };
          console.log( '_dataset', _dataset);

          processedDatasets.push( _dataset );
      }

      var chartScales = this.chartConfig['chartScales'];

      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);

          options['scales'] = chartScales;

          var legend: any ={};
          legend['display'] = true;       

          options['legend'] = legend;

          // Add ScaleLabel in options - Ends
      }

      if(_datasets.length == 0)
      {
          _chartConfig['datasets'] = processedDatasets;
      }
      else
      {
          for( var i = 0; i < _datasets.length; i++ ){

              Object.assign(_datasets[i], processedDatasets[i]);
          }
          _chartConfig['datasets'] = _datasets;

      }

      return _chartConfig;

  }
  cardLayoutConfig( chartConfig: any ) {
      console.log('chartConfig ==>', chartConfig);
  }


  public setImageNotFound(checkAltImage: any)
  {
      if ( this.chartConfig ) {
          if(checkAltImage)
          {
              var altImage = this.chartConfig['alt_image'];
              if( altImage )
              {
                  this.altImageSrc = altImage;
                  this.imageSrc = '';
                  this.imageNotFound = false;
              }
              else
              {
                  this.imageNotFound = true;
              }
          }
          else
          {
              this.altImageSrc = '';
              this.imageNotFound = true;
          }

      }
  }

  applyConfiguration(configData: any)
  {
    console.log('sss applyConfiguration>>'+configData, JSON.stringify(configData));
    var image = configData['image'];
    var titleHdrCol = configData['table_header'];
    var titleContentCol = configData['title_column'];

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

    if(configData['options']) {
        this.options = configData['options'];
    }

    this.chartHeaderTitle = this.chartParentData[titleHdrCol] || titleHdrCol || ''; //table_header : e.g. Product Group Details
    this.chartContentTitle = this.chartParentData[titleContentCol] || titleContentCol || ''; //title_column : e.g. PRODUCT_DESCR

    if( this.chartContentTitle )
    {
        var initials = this.chartContentTitle.match(/\b\w/g) || [];
        this.chartContentInitials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
    }
    console.log('chartContentInitials ===>', this.chartContentInitials);
  }

  FILTER_DATA(filterColumn: any, filterValue: any, data: any)
  {
      if( !filterColumn )
      {
          return data;
      }
      var sourceData = this.DEEP_CLONE(data);
      var filterData = sourceData.filter( (obj: any) => {
          if(obj[filterColumn] === filterValue){
            return obj;
          }
      });

      this.isTableData = (filterData.length > 0);

      return filterData;
  }

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

  performCustomCellAction(cellData: any)
  {
    console.log('inside bb-custom-table-panel performCustomCellAction', cellData);
    //this.onCustomCellAction.emit(cellData);
  }

  getThemeClass()
  {
      var themeClass = '';
      if(this.chartConfig && this.chartConfig['theme'])
      {
          themeClass = 'bg-' + this.chartConfig['theme'];
      }
      else
      {
          themeClass = 'bg-default';
      }
      themeClass = themeClass.toLowerCase();
      return themeClass;
  }
    setChartHeight()
    {
        var chartType = this.chartConfig['chartType'];
        var labels = this.chartConfig['labels'];
        var options = this.chartConfig['options'];
        if( options && options.height )
        {
            this.chartHeight = options.height; //Set Default height if not defined in Options
            this.chartCanvasHeight = options.height;
        }

        if( labels && options && options.displayTopBar && chartType == 'horizontalBar' )
        {
            var noOfBars = labels.length;
            var barChartCanvasHeight = (noOfBars < 5) ? ( options.height || 400 ) : ( ( noOfBars * 30 ) + 100 );
            console.log('setChartHeight >> ', noOfBars, barChartCanvasHeight, options);
            this.chartCanvasHeight = barChartCanvasHeight;
        }
    }
    
    buildPolarAreaChartData()
    {
          try 
          {
	    	    var polarAreaJson = this.chartConfig['polar_area_json'];
	    	    console.log('polarAreaJson     ..',polarAreaJson);
	            this.datasets = polarAreaJson['datasets'];
	            for(var i = 0; i < this.chartDataSource.length; i++)
	            {
	                if( this.chartDataSource[i]["LABEL"] && this.chartDataSource[i]["LABEL"] != '')
	                {
	                	this.labelsArr.push( this.chartDataSource[i]["LABEL"] );
	                }
	                if( this.chartDataSource[i]["DATA"] && this.chartDataSource[i]["DATA"] != '')
	                {
	                	this.dataArr.push( parseInt(this.chartDataSource[i]["DATA"]) );
	                }
	            }
	            this.datasets[0]['data'] = this.dataArr;
	            this.datasets['labels'] = this.labelsArr;
	            console.log('Data Array  :: ',this.dataArr,this.labelsArr,this.datasets);
         }
         catch (error) 
         {
            console.log('Exception in building pie chart data    ',error);
         }
    }
    
    buildCustomChartData()
    {
        console.log('Inside buildCustomChartData ..  ',this.chartDataSource);
    	try 
        {
            for(var i = 0; i < this.chartDataSource.length; i++)
            {
                if( this.chartDataSource[i]["DESCR"] && this.chartDataSource[i]["DESCR"] != '')
                {
                	this.labelsArr.push( this.chartDataSource[i]["DESCR"] );
                }
                if( this.chartDataSource[i]["CNT"] && this.chartDataSource[i]["CNT"] != '')
                {
                	this.dataArr.push( parseInt(this.chartDataSource[i]["CNT"]) );
                }
            }
            console.log('Data Array #07  :: ',this.dataArr,this.labelsArr);
        }
        catch (error) 
        {
            console.log('Exception in building pie chart data    ',error);
        }
    }


  //Added by SonamK
  formattedNumberValue: any;
    formatSummaryValues ( value: any, format: any ) 
    {
        const _win_ = (<any>window);

        if ( value.indexOf(':') == -1) {
            this.formattedNumberValue =  _win_.formattedValue( value, format ) ;
        }
        else {
            var title = value.slice( 0, value.indexOf(':') + 1 )
            var str = value.slice( value.indexOf(':') + 1, value.length );

            this.formattedNumberValue = title + ' ' + _win_.formattedValue( str, format ) ;
        }
        return this.formattedNumberValue;     
    }

    //Added by Pramod S on 16-APR-21 TODO [START]
    _onDrillDown(data: any)
    {
    //    console.log("bb-chart-panel.component onDrilldown",data);
    //    this.onDrillDown.emit(data);
    }
    //Added by Pramod S on 16-APR-21 TODO [END]
}
