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";
// import { Subscription } from 'rxjs/Subscription';
import { Subscription } from 'rxjs';

@Component({
  selector: 'bb-custom-tab-panel',
  templateUrl: './bb-custom-tab-panel.html',
  styleUrls: ['./bb-custom-tab-panel.css'],
  encapsulation: ViewEncapsulation.None
})

export class BBCustomTabPanel implements OnInit {

  constructor( private zone : NgZone ) { }
  @Input() tabDataSource : any;
  @Input() tabConfig : any;
  @Output() onDrillDownClose: EventEmitter<any> = new EventEmitter();

  //@Output() onCustomCellAction = new EventEmitter();

  isTableData = false;
  _tabData: any;

  tabHeaderTitle: any = '';
  tabClosebutton: any = '';
  tabContentTitle: any = '';
  tabContentInitials: any = 'NA';
  subscription: Subscription | any;
  subscriptionFV: Subscription | any;


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

  chartProps = {
      chartType: 'percentage',
      labels: [''],
      options: {
          percentFactorColumn: 'TARGET_VALUE',
          width: 16,
          height: 16,
          responsive: true,
          maintainAspectRatio: false,
          tooltip: false,
          cutOutPercentage: 0,
          condnFormat: [
            {
              id: "RED",
              expression: " data[0] <= 60 ",
              colors: [[252, 101, 101], [248, 248, 248]]
            },
            {
              id: "YELLOW",
              expression: " ( 61 <= data[0] ) && ( data[0] <= 80 ) ",
              colors: [[255, 211, 90], [248, 248, 248]]
            },
            {
              id: "GREEN",
              expression: " ( 81 < data[0] ) ",
              colors: [[0, 199, 153], [248, 248, 248]]
            }
          ]
       }
   };

  processedTabs: any = [];
  ngOnInit()
  {
       try {
      console.log('tabDataSource :: ', this.tabDataSource);
      console.log('tabConfig :: ', this.tabConfig);
        console.log('this.tabConfig[tabChartConfig] :: ', this.tabConfig['tabChartConfig']);
      var chartOptions = this.tabConfig
        var displayTopBar = false;
        if (  this.tabConfig['tabChartConfig'] !== undefined && this.tabConfig['tabChartConfig'] !== null)
        {
             console.log('inside the not undefined  sss :: ', displayTopBar);
            displayTopBar = this.tabConfig['tabChartConfig']['options']['displayTopBar'];
        }      
      console.log('displayTopBar :: ', displayTopBar);

        var detailModel = "";
        if (  this.tabConfig['tabs'][0]['data'] !== undefined && this.tabConfig['tabs'][0]['data'] !== null)
        {
                detailModel = this.tabConfig['tabs'][0]['data']['detailModel'];
                console.log('tabConfig :detailModel: ',detailModel);
        }    


      if( displayTopBar == true ) {
      var tabs =  this.tabConfig.tabs;
      console.log('tabs :: ' , tabs );
      var maxDataLimitArr: any = [];
      var maxLimit = 0;
      var tabsChartScales =  this.tabConfig.tabChartScales;
      console.log('tabsChartScales ::', tabsChartScales);

        var tooltipData ="";
         console.log(' this.tabConfig.tabChartConfig.options ::',  this.tabConfig.tabChartConfig);

        if (  this.tabConfig.tabChartConfig !== undefined && this.tabConfig.tabChartConfig !== null)
        {
                 tooltipData =  this.tabConfig.tabChartConfig.options.tooltips;
      			console.log('tooltipData ::', tooltipData);
	    }    

                                                


      for( var i = 0; i < tabs.length; i++ ) {

          //if( i == 0 ) {
            if(tabs[i]['datasets'] && tabs[i]['datasets'][0] && tabs[i]['datasets'][0]['data'] ) 
            {
                var dataArr = tabs[i]['datasets'][0]['data'];
                console.log('max :: ',  Math.max(...dataArr));
                var limit = Math.max(...dataArr);
                console.log('limit :: ', limit);
                maxDataLimitArr.push(limit);
            }

            if( maxDataLimitArr.length > 0 ) 
            {
                    maxLimit = Math.max(...maxDataLimitArr);
            }

            if( maxLimit <= 20 ) {
                maxLimit = maxLimit + 5;
            }
            else{
                maxLimit = Math.round(maxLimit + ( maxLimit * 35 /100 ));
            }

      if (   tabsChartScales !== undefined && tabsChartScales !== null)
         {          	  
            var yAxes = tabsChartScales['yAxes'][0];
            var ticks = yAxes['ticks'];

            console.log('ticks @@@ >>P > ', ticks, yAxes);
            ticks['max'] = maxLimit;

            console.log('ticks #### 22 >>> ', ticks);                
            // yAxes['ticks'] = ticks;   
            tabsChartScales['yAxes'][0]['ticks'] = ticks; 
          }       

            console.log('!!!!!!!!!!!! tabsChartScales :: ', tabsChartScales);
             if (  tabs[i]['chartConfig']!= null)
             {
            		tabs[i]['chartConfig']['options']['scales'] = tabsChartScales;
             }
            //tabs[i]['chartConfig']['options']['tooltips'] = tooltipData;

            var tabData = this.DEEP_CLONE(tabs[i]);
            
                 if (  tabs[i]['data'] !== undefined && tabs[i]['data'] !== null)
                {

                    tabs[i]['data']['detailModel'] = this.tabDataSource;
                }    

                var tabData = this.DEEP_CLONE(tabs[i]);

                if (  tabs[i]['chartConfig']!= null)
                {
            			tabData['chartConfig']['options']['tooltips'] = tooltipData;
		         }   

            this.processedTabs.push(tabData);
            //this.tabConfig['tabChartConfig']['options']['scales'] = tabsChartScales;
            //console.log('!!!!!!!!!!!! this.processedTabs :: ', this.processedTabs);
            console.log(tabs[i]);
        }
            // }
            console.log('processedTabs $$$$ ', this.processedTabs);
      }
      console.log('maxDataLimitArr :: ', maxDataLimitArr);
      this._tabData = this.DEEP_CLONE(this.tabDataSource);
      if( this.tabConfig )
      {
        this.applyConfiguration(this.tabConfig);
      }
      this.ngAfterViewInit();
  }
     catch(e) {
          console.log('tab panel ngonint exception ', e);
           if( this.tabConfig )
        {
            this.applyConfiguration(this.tabConfig);
        }
      }

  }

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

processedTabsEmpty: boolean = true;
  ngAfterViewInit() {
      try {
          console.log('ngAfterViewInit');
          if( this.processedTabs.length > 0 ) {
              this.processedTabsEmpty = false;
          }
          console.log('processedTabsEmpty ::', this.processedTabsEmpty);
          this.container = document.getElementsByClassName('tabContentTempl');

          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++) {

               console.log(' ** this. this.this.chartContainer.length ::',   this.chartContainer.length);
                console.log(' this.canvas[i] ::',    this.chartContainer[i] );
              if ( this.chartContainer[i] !== undefined &&  this.chartContainer[i] !== null )
              {
              		this.chartContainer[i].setAttribute('style','width:100%;height:191px;');
              		this.canvas.push(this.chartContainer[i].getElementsByTagName('canvas'));
                  console.log(' getElementsByTagName::',  this.chartContainer[i].getElementsByTagName('canvas'));
              }      
          }

          for(var i=0; i < this.canvas.length; i++) {
              console.log(' this.canvas[i][0] ::', this.canvas[i][0]);
              if (  this.canvas[i][0] !== undefined )
              {
                console.log(' this.canvas[i][0] nnot null::');
              this.canvas[i][0].setAttribute('style','width:100%;height:191px;');
          }
      }
      }
      catch(e) {
          console.log('exception e==>', e);
      }
  }

  tabChanged ( event: any ) {
      this.zone.run(( ) => {
          console.log('refresh view');
          this.ngAfterViewInit();
      });
  }

  applyConfiguration(configData: any)
  {
    var titleHdrCol = configData['table_header'];
    var titleContentCol = configData['title_column'];

    this.tabHeaderTitle = configData[titleHdrCol] || titleHdrCol || ''; //table_header : e.g. Product Group Details
    this.tabContentTitle = configData[titleContentCol] || titleContentCol || ''; //title_column : e.g. PRODUCT_DESCR
    //Added By Nilesh in case of tab in Ranking then close button is available Start :: 10-04-2021
    var closebutton = configData['closebutton'];
    this.tabClosebutton = closebutton;
    //Added By Nilesh in case of tab in Ranking then close button is available End :: 10-04-2021


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

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

  FILTER_DATA(filterColumn: any, filterValue: any, data: any)
  {
      if(!filterColumn)
      {
          return data;
      }
      var sourceData = this.DEEP_CLONE(data);
      var filterData = sourceData.filter( (obj: any) => {
          //console.log('ngOnChanges filterCompObjects obj: ', obj);
          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);
  }

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

  getThemeClass()
  {
      var themeClass = '';
      if(this.tabConfig && this.tabConfig['theme'])
      {
          themeClass = 'bg-' + this.tabConfig['theme'];
      }
      else
      {
          themeClass = 'bg-default';
      }
      themeClass = themeClass.toLowerCase();
      return themeClass;
  }
  closeDrillDown() {
    console.log('On Drill Down Close tabuler ');
    localStorage.removeItem('DrildropdownClick');
    this.onDrillDownClose.emit();
  }

  ngOnDestroy() 
  {
      console.log('DashboardComponentComponent 123 ngOnDestroy..');
      // unsubscribe to ensure no memory leaks
      if( this.subscription ) this.subscription.unsubscribe();
      if( this.subscriptionFV ) this.subscriptionFV.unsubscribe();
  }
}
