import { Component, OnInit, Input, Output, EventEmitter, ViewEncapsulation, HostBinding} from '@angular/core';
import { CurrencyFormatPipe } from '../../../../shared/pipes/currency-format-pipe';

import { RatingComponent } from '../../../../bb-rating/bb-rating.component';
import { getUserImage } from '../../composite.utils';

import { map } from 'rxjs/operators';
import { HttpRequestService }  from 'base-blocks';

import { HttpClient, HttpResponse, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
// import { Observable } from 'rxjs/Observable';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { DatePipe } from '@angular/common';
import { Overlay, OverlayConfig } from '@angular/cdk/overlay';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';


@Component({
  selector: 'bb-custom-card',
  templateUrl: './bb-custom-card.component.html',
  styleUrls: ['./bb-custom-card.component.css'],
  providers: [CurrencyFormatPipe]
})
export class BBCustomCard implements OnInit {

  //Added by Sonam K
  @Input() chartConfig : any;
  @Input() cards : any;
  @Input() card: any = {};
  @Input() template = "default";
  @Input() isSelection: any;
  @Output() onSelect: EventEmitter<any> = new EventEmitter();
  @Output() onPerformAction: EventEmitter<any> = new EventEmitter();
  hostUrl: any;
    _cards: any[] = [];

  @HostBinding('style.order') order: string | any;
  
  imageInitials = 'NA';
  profileImageSrc: any;
  altProfileImageSrc: any;

  imageNotFound = false;
  
  //Added by Sonam K
  multipleChartsConfig: any = [];
  chartCanvasHeight = 191; 
  chartsCount: any;
  
  constructor() { }

  bgColorCSS: any ;
  ngOnInit() {
    console.log('BBCustomCard ngOnInit :: card', this.card);
    console.log('chartConfig >>', this.chartConfig);
    console.log('cards >>', this.cards);
    this.hostUrl= this.getHostURL() ;
    console.log('this.hostUrl >>', this.hostUrl);

   
    this._cards = Object.assign([], this.cards);

    if ( this.chartConfig ) {
        var charts = this.chartConfig['chartConfig'];
        this.chartsCount =  charts.length;
        for ( var i = 0; i < charts.length; i++ ) {
            console.log('i >>>', i);
            console.log(charts[i]);
            var chart = charts[i];
            var chartConfiguration = this.buildMultipleChartsData( chart );
            this.multipleChartsConfig.push( chartConfiguration );
        }

        this.bgColorCSS = this.chartConfig['customCss'];
        console.log('bgColorCSS >>', this.bgColorCSS);
        console.log(typeof(this.bgColorCSS));

    }

    if( this.card && this.card['order_column'] )
    {
      try
      {
        this.order = '' + parseInt(this.card[this.card['order_column']]);
      }
      catch(e)
      {
        this.order = '0';
      }
      console.log('this.order', this.order);
    }
    if( this.card && this.card['selected'] == true )
    {
      console.log('Default card selected ...');
      this.emitSelection();
    }
    this.initImage();
  }

  setUserImage( empCode: any ) {
      console.log('empCode >>', empCode);
      return getUserImage( empCode );
  }

 // Added by Pravin K on 18-MAR-20 [To add-task popup]  START	  
  emitSelection( event?:any )
  { 
      console.log("emitSelection emit:",event);
      if(event){
          console.log("card:",this.card);
          if(this.card["user_action"] && this.card["user_action"] == 'ADD_TASK')
           {
              console.log("open userTask");
              var link = {
                  AutoInvoke: "",
                  DisplayMode: "1",
                  FormNo: "1",
                  LineNo: "1",
                  LinkForm: "LINK",
                  LinkType: "A",
                  RecordSpecific: "1",
                  TargetObject: "user-task",
                  linkId: "",
                  feedData: this.card
              };
              this.onPerformAction.emit(link); 
           }
      }
      else 
      {  
        if( this.isSelection ){

            console.log(" this.isSelection :",this.isSelection);
            console.log(" before card 138:",this.card);
            this.onSelect.emit(this.card);
            localStorage.removeItem('DrildropdownClick')
           
           
            console.log(" After  card isSelection:",this.card);
        } 
      } 
  } 
// Added by Pravin K on 18-MAR-20 [To add-task popup]  END
   
  //Added by Sonam K - START
  ngAfterViewInit() { 
      console.log('Inside ngAfterViewInit()');
      var charts = document.getElementsByClassName('series-custom-card');
      console.log('charts >>', charts);

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

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

            charts[i].setAttribute('style','width:' + chartWidth + '%;');
        }
      }
  }
  //Added by Sonam K - END
   
  public setErrorImage(bannerImg: any)
  {
      bannerImg.src = 'dashboard/assets/images/svg/avatar-self.svg';
      bannerImg.style.width = '48px';
      bannerImg.style.height = '48px';
  }
  
  public setErrorImageCard(cardImg: any,value: any)
  {
      cardImg.src = '/ibase/CustomMenuImageServlet?fldValue='+value+'&object=slpers&objName=slpers';
      cardImg.style.width = '48'
      cardImg.style.height = '48px';
  }  
  public setImageNotFound(checkAltImage: any)
  {
      if(checkAltImage)
      {
          var imageAltSrc = this.card['alt_image'];
          if( imageAltSrc )
          {
              this.altProfileImageSrc = imageAltSrc;
              this.profileImageSrc = ''; 
              this.imageNotFound = false;
          }
          else
          {
              this.imageNotFound = true;
          }
      }
      else
      {
          this.altProfileImageSrc = ''; 
          this.imageNotFound = true;
      }
  }

  private initImage()
  {
      console.log(' before Name : ');
      
      var imageSrc = this.card['image'];
      console.log('imageSrc : ', imageSrc, ' this.profileImageSrc : ', imageSrc);
      if( imageSrc )
      {
          this.profileImageSrc = ( imageSrc.indexOf('/') == -1 ) ? 'dashboard/assets/images/svg/'+ imageSrc : imageSrc;
      }
      var name = this.card[this.card['title_column']];
      if( name )
      {
          var initials = name.match(/\b\w/g) || [];
          this.imageInitials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
      }
      //console.log('Name : ', name, ' this.imageInitials : ', this.imageInitials);
      //console.log('imageNotFound : ', this.imageNotFound, ' this.profileImageSrc : ', this.profileImageSrc);
  }
  public getThemeClass()
  {
      var themeClass = '';
      if(this.card && this.card['theme_column'] && this.card[this.card['theme_column']])
      {
          themeClass = 'bg-' + this.card[this.card['theme_column']];
      }
      else
      {
          themeClass = 'bg-default';
      }
      if( this.card && this.card['image_size'] && this.profileImageSrc )
      {
          themeClass = themeClass + ' ' + this.card['image_size']; 
      }
      if( this.card && this.card['alt_image_size'] && this.altProfileImageSrc )
      {
          themeClass = themeClass + ' ' + this.card['alt_image_size']; 
      }
      themeClass = themeClass.toLowerCase();      
      return themeClass;
  }

  public getBadgeThemeClass()
  {
      var themeClass = '';
      var badgeThemeCol = this.card['badge_theme_column'];
      if(this.card && this.card['badge_theme'])
      {
          themeClass = 'bg-' + this.card['badge_theme'];
      }
      else if(this.card && badgeThemeCol && this.card[badgeThemeCol])
      {
          themeClass = 'bg-' + this.card[badgeThemeCol];
      }
      else
      {
          themeClass = 'bg-default';
      }
      return themeClass;
  }
  
  //Added by Sonam K - START
  multipleChartsDataArr: any = [];
  chartDataSource: any =[];
  chartInfoColumn: any;

  legendArray: any = [];

  //customCSS : boolean = false;
  buildMultipleChartsData( chartConfig: any ) {
      console.log(' chartConfig >>>', chartConfig);
      var data = chartConfig;
      var filterColumn = data['title_column'];
   
   /*   this.customCss = data['customCSS'];
      console.log('customCss **** >>', this.customCss);*/

      var chartType = data['chartType'];
      var dataArr: any = [];
      var horizontalBarData = [];

      for ( var i = 0; i < this.cards.length; i++ ) {
          var chart = this.cards[i];
          var chartTitle = chart['TITLE'];
          var cType = chart['CHART_TYPE'];

          if ( filterColumn == chartTitle ) {
              if ( chartType == cType ) {
                  dataArr.push(chart);
              }
          }
      }

      var processedDataset = this.buildDatasets( data, chartType, dataArr );
      console.log('processedDataset  &&&&& >>>>>', processedDataset);

      this.multipleChartsDataArr.push(processedDataset);

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

      for ( var i = 0; i < this.multipleChartsDataArr.length; i++ ) {
         var cType: any = this.multipleChartsDataArr[i]['chartType'];
         console.log('cType >>', cType);

         if( cType == 'horizontalBar' ) {

            var labels: any = this.multipleChartsDataArr[i]['labels'];
            var values = this.multipleChartsDataArr[i]['datasets'][0]['chartTextArr'];

            console.log(' labels  >>', labels);
            console.log(' values  >>', values);

            var legendsDescrImageArr = [
                {
                    "legend": "Not Visited",
                    "image":"dr_not_met.svg"
                },
                {
                    "legend": "Visited Once",
                    "image":"visit_1.svg"
                },
                {
                    "legend": "Visited 2 Times",
                    "image":"visit_2.svg"
                },
                {
                    "legend": "Visited 3 Times",
                    "image":"visit_3.svg"
                },
                {
                    "legend": "Visited 4 Times",
                    "image":"visit_1.svg"
                },
                {
                    "legend": "Visited 5 Times",
                    "image":"visit_1.svg"
                }
            ];
            console.log('legendsDescrImageArr >>', legendsDescrImageArr);
            var count = 0;
            for ( var j = 0; j < labels.length; j++ ) {
                console.log('j >>>', j, ' count >>', count );

               // var chartTextStr = labels[j] + ':' + values[j];
                var labelStr = labels[j]; 
                var labelVal = values[j];
                var legendsImageObj = {};
            
                legendsImageObj = {
                    "legend": labelStr,
                    "legendVal": labelVal
                   // "image": labelImg
                };
                console.log('legendsImageObj  @@ >>', legendsImageObj);

                /*
                var labelStr; var labelImg;
                for ( var k = 0; k < legendsDescrImageArr.length; k++ ) {

                    labelStr = legendsDescrImageArr[k]['legend'];
                    console.log('labelStr  @@ >>', labelStr);

                    if( labelStr == labels[j] ){
                        labelImg = legendsDescrImageArr[k]['image'];                        
                    }

                    legendsImageObj = {
                        "legend": labelStr,
                        "legendVal": labelVal,
                        "image": labelImg
                    }
                }*/

                /*
                var chartTextStr = '';
                var chartTextStr1 = '';
                if ( j == 0 ) {
                    chartTextStr = labels[j] + ' : ' + values[j];
                    console.log('j #1 >>', j);
                   // j = j + 1;
                    count = j + 1 ;
                    chartTextStr1 = labels[count] + ' : ' + values[count];
                    console.log('j #2 >>', j);                    
                    console.log('count #1 >>', count);

                    console.log('count #2 >>', count);
                    
                }
                else{
                    console.log('j #2>>>', j, ' count >>', count );

                    if( count == j ) {
                        count = count + 1;
                        chartTextStr = labels[count] + ' : ' + values[count];
                        console.log('j #1 >>', j);
                    // j = j + 1;
                        count = count + 1 ;
                        chartTextStr1 = labels[count] + ' : ' + values[count];
                        console.log('j #2 >>', j);                    
                        console.log('count #1 >>', count);

                        console.log('count #2 >>', count);
                    }
             
                }
                var text = chartTextStr + chartTextStr1;
                console.log('text >>', text);
                this.legendArray.push( text );*/

                
                
                this.legendArray.push( legendsImageObj );
            }
         }
      }

      console.log(' legendArray >>>', this.legendArray);
      return data;
    }
    
    visitInfoColumn: any;
    drCountColumn: any;

    customFontColorCSS: boolean = false;

        buildDatasets( chartConfig: any, chartType: any, chartDataSource: any ) {

      console.log('chartConfig >>', chartConfig, 'chartType >>', chartType ,'chartDataSource >>', chartDataSource);
      this.chartDataSource.push(chartDataSource);
      if ( chartConfig['chart_info_column'] ) {
        if( chartDataSource.length > 0 ) {
            this.chartInfoColumn = chartDataSource[0][chartConfig['chart_info_column']];            
        }
      }
       if ( chartConfig['visit_info_column'] ) {
        if( chartDataSource.length > 0 ) {
            this.visitInfoColumn = chartDataSource[0][chartConfig['visit_info_column']];            
        }
      }
      if ( chartConfig['dr_info_column'] ) {
        if( chartDataSource.length > 0 ) {
            this.drCountColumn = chartDataSource[0][chartConfig['dr_info_column']];            
        }
      }

      var chartDatasets = chartConfig['datasets'];
      var options = chartConfig['options'];
      this.chartCanvasHeight = options['height'];
      var _dataset = {};
      var _data_ = {};
      var processedDatasets: any =[];
      var chartCenterText = ' ';
      var chartCenterTextColor = "black";
      var chartCenterTextFont = "12px  Roboto,sans-serif";
      var chartCenterTextColor2 = "gray";
      var processedDataArr = [];
      var peocessedLabelsArr: any = [];
      var datasetCount = 0;
      var datasetInfoArray: any = [];

      console.log('options ### >>', options);

      console.log('options[displayTopBar] ### >>', options['displayTopBar']);

        var _displayTopBar = options['displayTopBar'];
    
      if ( _displayTopBar == true ) {
        console.log('#############');
        if( chartConfig['chartText'] ) {
            console.log('$$$$$$$$$$$$$$');
            if( chartDataSource ) {
                var chartTextStr ;
                if( chartDataSource[0] ) {
                    chartTextStr = chartDataSource[0][chartConfig['chartText']];
                }
                console.log('chartTextStr $$$>>', chartTextStr);
                console.log(typeof(chartTextStr));

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

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

      if( chartConfig['datasetCountBasedOn'] && chartDataSource.length > 0 ) {
          var datasetCountInfo;
        for ( var i =0; i <  chartDataSource.length; i++ ) {
            datasetCountInfo = chartDataSource[i][chartConfig['datasetCountBasedOn']];
            if(typeof(datasetCountInfo) === 'string' ) {
                datasetCountInfo = JSON.parse(datasetCountInfo);
            }

            for ( var k = 0; k < datasetCountInfo.length; k++ ) {
                datasetInfoArray.push(datasetCountInfo[k]);
            }
            /*
            if( datasetCountInfo.length > datasetCount ) {
                datasetCount =  datasetCountInfo.length;
            }*/
        }

        const unique = (value: any, index: any, self: any) => {
        return self.indexOf(value) === index
     }

        console.log('datasetInfoArray >>', datasetInfoArray);
        datasetInfoArray = datasetInfoArray.filter(unique);
        console.log('datasetInfoArray #2>>', datasetInfoArray);

        console.log('chartDataSource >>>>', chartDataSource);

        console.log('chartConfig >>>>', chartConfig);

        for ( var i =0; i <  chartDataSource.length; i++ ) {
            console.log('chartDataSource #2 >>>>', chartDataSource);

            var datasetCountArray: any = [];
            var VISIT_INFO = [];
            var VISIT_COUNT = [];

            for ( var k = 0; k < datasetInfoArray.length; k++ ) {
                datasetCountArray.push("0");
            }

            var visitInfoArray = chartDataSource[i]['VISIT_INFO'];
            if(typeof(visitInfoArray) === 'string' ) {
                visitInfoArray = JSON.parse(visitInfoArray);
            }

            var visitCountArray = chartDataSource[i]['VISIT_COUNT'];
            if(typeof(visitCountArray) === 'string' ) {
                visitCountArray = JSON.parse(visitCountArray);
            }

            for ( var k = 0; k < datasetInfoArray.length; k++ ) {
                for( var j = 0; j < visitInfoArray.length; j++ ) {
                    if ( datasetInfoArray[k] ==visitInfoArray[j] ) {
                        datasetCountArray.splice(k, 1, visitCountArray[j]);
                    }
                }               
            }

            VISIT_INFO = datasetInfoArray;
            VISIT_COUNT = datasetCountArray;
            chartDataSource[i]['VISIT_INFO'] = VISIT_INFO;
            chartDataSource[i]['VISIT_COUNT'] = VISIT_COUNT;
        }
      }

     var customDataset: any = [];
     var createDataset = false;

      var processDataset = true;

      if( chartConfig['processDataset']  ) {

        processDataset = chartConfig['processDataset'];
      }

      console.log('datasetInfoArray >>>', datasetInfoArray);
      datasetCount = datasetInfoArray.length;

     if (  datasetCount &&  datasetCount > 0  ) {
        createDataset = true;
        var datasetFormat = chartDatasets[0];

        for ( var i = 0; i < datasetCount; i++ ) {
           customDataset.push(datasetFormat);
        }

        chartDatasets = customDataset;
      }

      if ( chartConfig['chartType'] == 'doughnut' )
       {
            if ( chartConfig['chart_center_text'] ) 
            {
                var chartCenterTextColumn = chartConfig['chart_center_text'];

               var customCSS = chartConfig['customCSS'];
                console.log('customCSS >>>>', customCSS);

                var customFontColor = chartConfig['customFontColor'];
                console.log('customFontColor >>>>', customFontColor);
                var bgColorClass = chartConfig['bgColorClass'];
                console.log('bgColorClass >>>>', bgColorClass);

                if( customFontColor ) {
                    this.customFontColorCSS = true;
                }
                else{
                     this.customFontColorCSS = false;
                }

                if( chartCenterTextColumn ) {
                    if( chartDataSource.length > 0 ) {
                      var chartCenterTextArr = chartDataSource[0][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 ='';
                            if( customCSS ) {
                                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);
                                }
                                console.log( 'i >>>>', i, 'labelIndex >>', labelIndex, 'labelIndex1 >>', labelIndex1);
                            }
                            else{
                                chartCenterTextColor = chartCenterTextColor;
                                chartCenterTextFont = chartCenterTextFont;
                            }
                            
                            if( customFontColor ) {
                                chartCenterTextColor = customFontColor;
                                chartCenterTextColor2 = customFontColor;
                            }
                            else{
                                chartCenterTextColor = chartCenterTextColor;
                                 chartCenterTextColor2 = chartCenterTextColor2;
                            }
                            if(  i > 1 ) {
                                //TODO 
                                //return; 
                                break;
                            }
                            if ( i == 0 ) {

                                if( customCSS ) {
                                    options['chartCenterText'] = text1;
                                    options['chartCenterTextColor1'] = chartCenterTextColor;
                                    options['chartCenterTextFont1'] = "bold 18px Arial, Helvetica, sans-serif ";
                                    options['chartCenterText2'] = text2;
                                    options['chartCenterTextColor2'] = chartCenterTextColor2;
                                    options['chartCenterTextFont2'] = "14px  Arial, Helvetica, sans-serif";

                                }else{
                                options['chartCenterText'] = chartCenterText;
                                options['chartCenterTextColor1'] = chartCenterTextColor;
                                options['chartCenterTextFont1'] = chartCenterTextFont;
                            }
                            }
                            else {
                                if ( customCSS ){
                                    options['chartCenterText3'] = text1;
                                    options['chartCenterTextColor3'] = chartCenterTextColor;
                                    options['chartCenterTextFont3'] = "bold 18px Arial, Helvetica, sans-serif ";
                                    options['chartCenterText4'] = text2;
                                    options['chartCenterTextColor4'] = chartCenterTextColor2;
                                    options['chartCenterTextFont4'] = "14px  Arial, Helvetica, sans-serif ";
                                }
                                else {
                                options['chartCenterText2'] = chartCenterText;
                                options['chartCenterTextColor2'] = chartCenterTextColor;
                                options['chartCenterTextFont2'] = chartCenterTextFont;
                            }
                        }
                    }
                }
            }
            }

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

                    var labelColumn = chartDatasets[i]['labels'];
                    var bgColorColumn = chartDatasets[i]['backgroundColor'];
                    var dataArray: any = [];
                    for( var k = 0; k < dataColumn.length; k++ ) {
                        dataArray.push(chartDataSource[0][dataColumn[k]]);
                    }

                    console.log('dataArray >>>', dataArray);

                    var labelsArray: any = [];
                    for( var k =0; k < labelColumn.length; k++ ) {
                        labelsArray.push(labelColumn[k]);
                    }

                    var bgColorsArr: any =[];
                    for( var k = 0; k < bgColorColumn.length; k++ )
                    {
                            bgColorsArr.push(bgColorColumn[k]);
                    }
    
                    _dataset = {
                        'data' : dataArray,
                        'labels' : labelsArray,
                    // 'titles' : titlesArr,
                        'backgroundColor' : bgColorsArr,
                    // 'label': dataColumnDescr
                    };
                    console.log( '_dataset', _dataset);

                    processedDatasets.push( _dataset );
                }
                chartConfig['datasets'] = processedDatasets;
            }//End of for loop
            
            chartConfig['options'] = options;
            chartConfig['bgColorClass'] = bgColorClass;    
        } 
        else if ( chartConfig['chartType'] == 'horizontalBar' )
        {
            console.log('chartDatasets ## >>>>', chartDatasets);
            for( var i = 0; i < chartDatasets.length; i++ )
            {
                var dataColumn = chartDatasets[i]['y_column'];
                console.log('dataColumn ## >>>>', dataColumn);

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

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

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

                 console.log('chartDataSource >>>', chartDataSource);

                var backgroundColor;
                var backgroundColorColumn = chartConfig['backgroundColor'];
                console.log('backgroundColorColumn >>>', backgroundColorColumn);

                var dataColumnDescr ;
                var bgColorsArr: any =[];

                if ( createDataset ) {
                    // var backgroundColorColumn = chartDataSource.map((_chartData => {
                    //     backgroundColor =  backgroundColorColumn[i];
                    // }) );
                    var backgroundColorColumn = chartDataSource.map((_chartData: any) => {
                        backgroundColor =  backgroundColorColumn[i];
                    } );
                }
                else {
                    backgroundColor = backgroundColorColumn;
                }

                if ( createDataset ) {
                    // var legendsColumn = chartDataSource.map((_chartData => {
                    //     if(typeof(_chartData[legendsColumnDescr]) === 'string' ) {
                    //         var temp = JSON.parse(_chartData[legendsColumnDescr]);
                    //     }
                    //     else{
                    //         var temp = _chartData[legendsColumnDescr];
                    //     }
                    //     if( temp ) {
                    //         dataColumnDescr = temp[i];
                    //         return dataColumnDescr;
                    //     }
                    // }) );
                    var legendsColumn = chartDataSource.map((_chartData: any) => {
                        if(typeof(_chartData[legendsColumnDescr]) === 'string' ) {
                            var temp = JSON.parse(_chartData[legendsColumnDescr]);
                        }
                        else{
                            var temp = _chartData[legendsColumnDescr];
                        }
                        if( temp ) {
                            dataColumnDescr = temp[i];
                            return dataColumnDescr;
                        }
                    } );
                }
                else {
                    dataColumnDescr = legendsColumnDescr;
                }

               if ( createDataset ) {
                    // var dataArr = chartDataSource.map((_chartData => {
                    //     if(typeof(_chartData[dataColumn]) === 'string' ) {
                    //         var temp = JSON.parse(_chartData[dataColumn]);
                    //     }
                    //     else {
                    //         var temp = _chartData[dataColumn];
                    //     }

                    //     if( temp ) {
                    //         return temp[i];
                    //     }
                    // }) );
                    var dataArr = chartDataSource.map((_chartData: any) => {
                        if(typeof(_chartData[dataColumn]) === 'string' ) {
                            var temp = JSON.parse(_chartData[dataColumn]);
                        }
                        else {
                            var temp = _chartData[dataColumn];
                        }

                        if( temp ) {
                            return temp[i];
                        }
                    } );
                }
                else{
                    // var dataArr = chartDataSource.map((_chartData => {
                    //         return _chartData[dataColumn];
                    // }) );
                    var dataArr = chartDataSource.map((_chartData: any) => {
                        return _chartData[dataColumn];
                    } );
                }

                // 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 chartTextArr = chartDataSource.map((_chartData => {
                //     console.log(' _chartData  >>', _chartData);
                //     if( _chartData ) {
                //     return _chartData[chartTextColumn];
                //     }
                // }) );
                var chartTextArr = chartDataSource.map((_chartData: any) => {
                    console.log(' _chartData  >>', _chartData);
                    if( _chartData ) {
                    return _chartData[chartTextColumn];
                    }
                } );

                console.log('chartTextArr >>', chartTextArr);
                /*console.log('labelsArr >>', labelsArr);
                var labelsValArr = [];
                for ( var p = 0; p < labelsArr.length; p++ )
                {
                    var valLbl = chartTextArr[p]+" "+labelsArr[p];
                    labelsValArr.push(valLbl);
                }
                console.log('Length of Text and Label ....',chartTextArr.length, labelsArr.length);
                console.log('labelsValArr .... ',labelsValArr);
                chartConfig['labels'] = labelsValArr;*/

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

                    backgroundColor = bgColorsArr;

                    dataArr = chartTextArr;
                    
                    }
                var _labelsArray = [];
                var _bgColorArray = [];

                if(! createDataset ) {
                    _labelsArray = chartConfig['labelsArr'];
                    console.log('_labelsArray >>>>', _labelsArray);

                    _bgColorArray = chartConfig['backgroundColor'];
                    console.log('_bgColorArray >>>>', _bgColorArray);

                    console.log('dataArr #1 >>', dataArr);
                    console.log('backgroundColor #1 >>', backgroundColor);
                    var labels_ = [];
                    var colors_ =[];


                    for( var y = 0; y < labelsArr.length; y++ ) {
                        console.log('chartTextArr >>>', labelsArr[y]);
                        for ( var x = 0; x < _labelsArray.length; x++ ) {
                            console.log('_labelsArray[x] >>', _labelsArray[x], x, y);
                            if( _labelsArray[x] == labelsArr[y] ) {
                                labels_.push( _labelsArray[x] );
                                colors_.push( _bgColorArray[x] );
                            }
                           // break;
                        }
                    }
                    labelsArr = labels_;
                    backgroundColor = colors_;
                    console.log('labels_ #2 >>', labels_);
                    console.log('colors_ #2 >>', colors_);
                }               
                    
                console.log('backgroundColor >>', backgroundColor);

                _dataset = {
                    'chartTextArr' : chartTextArr,
                    //'data' : _data_,
                    'data' :  dataArr, 
                    'labels' : labelsArr,
                    'titles' : dataColumnDescr,
                    'dataSource' : '',
                    'label': dataColumnDescr,
                    'backgroundColor':backgroundColor
                };
                console.log( '_dataset', _dataset);

                processedDatasets.push( _dataset );
                /*
                if( createDataset ) {
                    processedDatasets.push( _dataset );
                }
                else {
                    processedDatasets.push( _data_ );
                }*/
            }

            console.log('processedDatasets >>', processedDatasets);
            chartConfig['datasets'] = processedDatasets;
            chartConfig['data'] = _data_;
           // chartConfig['data'] = processedDatasets;
            var chartScales = 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;

          // Add ScaleLabel in options - Ends
        }
     }
     return chartConfig;
    }
    openTransactionDocGWT( camId: any,brandCode: any )
    {
        console.log('inside the openTransactionDocGWT method nil');
        try
      {
           console.log('inside the openTransactionDocGWT method nil inside try ');
        (<any>window).openTransactionPoupupGWT((<any>window).Math.random(),'sprs_campgn_wiz','W','sprs_campgn_wiz',camId,brandCode)
          console.log('inside the openTransactionDocGWT method nil inside try After Call ');
      }
      catch(e)
      {
           console.log('inside the openTransactionDocGWT method nil inside Catch ');
           console.log( " Exception in ts openTransactionDocGWT ",e); 
           //openTransactionPoupupGWT('123456','sprs_campgn_wiz','W','sprs_campgn_wiz',camId,brandCode)
            console.log('inside the openTransactionDocGWT method nil inside Catch After ');
      }
       
    }
    openTransactionRxGWT( camId: any,brandCode: any )
    {

         try
      {
           console.log('inside the openTransactionRxGWT method nil inside try ');
        (<any>window).openTransactionPoupupGWT((<any>window).Math.random(),'sprs_campgn_rx_wiz','W','sprs_campgn_rx_wiz',camId,brandCode)
          console.log('inside the openTransactionRxGWT method nil inside try After Call ');
      }
      catch(e)
      {
           console.log('inside the openTransactionRxGWT method nil inside Catch ');
           console.log( " Exception in ts openTransactionRxGWT ",e); 
           //openTransactionPoupupGWT('123456','sprs_campgn_rx_wiz','W','sprs_campgn_rx_wiz',camId,brandCode)
            console.log('inside the openTransactionRxGWT method nil inside Catch After ');
      }
       
    }

    getDashboardMetadataFromCard (metadataName:string,card: any,sales_pers: any)
    {
             
              console.log( "getDashboardMetadataFromCard>>>>> before this.cards nil" , this.card); 
              

               var compDataLocal: any = [];
                try{
                    compDataLocal = JSON.parse(JSON.stringify(this.card));
                }
                catch(e){
                                console.log("onSelect of card Nilesh *** ");

                }

                console.log("onSelect of card Nilesh af ** ",compDataLocal);
                 
             

            try{
            compDataLocal = compDataLocal.map( (data: any) => {
               
                data['selected'] = true;
                  console.log("onSelect of card after Nilesh  ", data);
                return data;
            });
              }
                catch(e){
                                console.log("onSelect of card Nilesh 2154 412410 *** ");

                }   
            console.log( "getDashboardMetadataFromCard after >>>>> this.card nil compDataLocal " , compDataLocal); 
              
            console.log( "getDashboardMetadataFromCard>>>>> this.metadataName" , metadataName); 

            //  var brandSOcard = 'brandSOCard_'+ sales_pers;
            //   console.log( "getDashboardMetadataFromCard>>>>> this.brandSOcard Befiore" , brandSOcard); 
            //   console.log( "document.getElementById(brandSOcard) Aftwer" , document.getElementById(brandSOcard)); 
            //   if (document.getElementById(brandSOcard)!==undefined && document.getElementById(brandSOcard)!==null )
            //   {
                
            //     console.log( "getDashboardMetadataFromCard>>>>> this.brandSOcard if nil " , brandSOcard); 

            //     document.getElementById(brandSOcard).classList.add('custom-card-brand-selected');
            //     console.log( "getDashboardMetadataFromCard>>>>> this.brandSOcard if nil Before " , document.getElementById(brandSOcard));
            //   } 
            var drillColumnName = "";
            var drillColumnValue = "";
            //  this.cards = Object.assign([], this.cards);
            //  console.log( "getDashboardMetadataFromCard>>>>>  this._cards " , this.cards); 
            // this.cards = this.cards.map((c) => {

            // console.log("onSelect of  getDashboardMetadataFromCard card ", c);
            // if( c === card)
            // {
            //     c['selected'] = true;
            // }
            // else
            // {
            //     c['selected'] = false;
            // }
            // console.log("onSelect of getDashboardMetadataFromCard card after ", c);
            // return c;
            // });
            //  console.log("onSelect of  getDashboardMetadataFromCard this._cards ", this.cards);
            try
            {
                var selectedFieldInfo: any = {
                "link_metadata" : metadataName,
                "rowData" : compDataLocal
                };
            }
            catch(e)
            {  
                console.log( " Exception in ts getDashboardMetadataFromCard ",e); 

            }     

            console.log( "getDashboardMetadataFromCard>>>>> this.selectedFieldInfo nil compDataLocal " , selectedFieldInfo); 

            this.onSelect.emit(selectedFieldInfo);

            
            //   console.log( "getDashboardMetadataFromCard>>>>> this.brandSOcard Aftwer" , brandSOcard); 
            //   console.log( "document.getElementById(brandSOcard) Aftwer" , document.getElementById(brandSOcard)); 
            //   if (document.getElementById(brandSOcard)!==undefined && document.getElementById(brandSOcard)!==null )
            //   {
                
            //     console.log( "getDashboardMetadataFromCard>>>>> this.brandSOcard if nil " , brandSOcard); 

            //     document.getElementById(brandSOcard).classList.add('custom-card-brand-selected');
            //     console.log( "getDashboardMetadataFromCard>>>>> this.brandSOcard if nil " , document.getElementById(brandSOcard));
            //   } 
           
        //     var metadataUrl =  this.SERVICE_URL + metadataName;  
        //     var headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        //     var options = { headers: headers };
        //     console.log( "getDashboardMetadataFromCard>>>>>" + metadataUrl); 
           
        //    // var userName = localStorage.getItem('userName') || '';
        //     //var dashboardMetadata = localStorage.getItem(metadataName+userName);
        //     // if(!dashboardMetadata)
        //     // {
        //         console.log("getDashboardMetadataFromCard dashboard metadata not found in local storage");
        //         this.http.get<any>( metadataUrl, options).pipe( map( (result) => this.extractDashboardData(result, metadataName) ) ).subscribe(
        //             result => {


        //         // var datasource = result.datasource;
        //         // var filters =  result.filters;
        //         // this.dashboardService.createDataSources(metadataName,datasource,filters);
                
        //         // this.drillDownContainer.detach();
        //         // var compFactory =  this._componentFactoryResolver.resolveComponentFactory(DashboardViewComponent)
        //         // this.compRef = this.drillDownContainer.createComponent(compFactory);
        //         // this.compRef.instance.compRef = this.compRef;
        //         // this.compRef.instance.viewData = result.view[0];
        //         // this.compRef.instance.metadataname = metadataName;
        //         // //this.compRef.instance.filterInfo = selectedFieldInfo;
        //         // this.compRef.instance.isDrillDown = true;
        //         // this.compRef.instance.isCompositeDrillDown = selectedFieldInfo.isCompositeDrillDown;
        //         // this.compRef.instance.filters = result.filters;
        //         // this.compRef.instance.onDrillDownClose = new EventEmitter();
        //         // this.compRef.instance.onDrillDownClose.subscribe(
        //         //   event => {
        //         //       console.log('On Drill Close Event',this.compRef);
        //         //       this.compRef.destroy();
        //         //   }
        //         // );
        //             }
        //         );
        //     // }
    }

    private extractDashboardData(res: HttpResponse<any> | any, metadataName: any) {
       // var body = res.json();
        var userName = localStorage.getItem('userName') || '';
        console.log('extractData[' + JSON.stringify(res) + '] userName:['+userName+']');
     
        //this.userInfo = res['USER_INFO'];
        //this.userInfo = res['DASHBOARD_USER_DETAILS'];
        //Added by Pankaj T. on 24-08-2020 to resolved vulnerability sensitive information disclosure from local storage - start
        delete res['DASHBOARD_USER_DETAILS'];
        //Added by Pankaj T. on 24-08-2020 to resolved vulnerability sensitive information disclosure from local storage - end
        localStorage.setItem(metadataName+userName, JSON.stringify(res));
        return res || { };
    }

      public getHostURL(): string {
        // var HOST_URL: string = '';
        var HOST_URL: any = '';
        HOST_URL = localStorage.getItem( 'HOST_URL' );
        //if ( !HOST_URL ) HOST_URL = '';
        //Added by sunny soni for native related change for handling server call[Start]
        if ( !HOST_URL ) {
            HOST_URL = '';
            HOST_URL = localStorage.getItem( 'host_url' );
            if ( !HOST_URL ) HOST_URL = '';  
        }
        //Added by sunny soni for native related change for handling server call[End]
        console.log( 'getHostURL New Nilesh [', HOST_URL, ']' );
        return HOST_URL;
    }

        
}
