import { Component, Input, ViewChild, NgZone } from '@angular/core';
import { WebdatarocksComponent } from '../webdatarocks/webdatarocks.component';
import {  RESIZE_EVENT } from '../window-resize';
import { DashboardService } from '../../dashboard/dashboard.service';

declare var exportToFile :any;

@Component({
  selector: 'wbr-simple-grid',
  templateUrl: './wbr-simple-grid.component.html',
  styleUrls: ['./wbr-simple-grid.component.css']
})
export class WbrSimpleGridComponent {
    @Input('data') reportData : any;
    @Input('elWidth') elWidth: any;
    @ViewChild('wdrSimpleGrid') wdrSimpleGrid: WebdatarocksComponent | any;  

    report: any;
    columnsConfig: any;
    showExport: any;
    clientWidth: any;
    hostUrl: any;
    linkedColumns: any = [];
    selectedRowIndex: any;
    selectedRowData: any={};
    customizeCellFunc = this.customizeCellFunction.bind(this);
    
    constructor(private dashboardService: DashboardService, public zone: NgZone){}

    ngOnInit() { 
        console.log('webdatarocks component called ', this.reportData, 
        this.wdrSimpleGrid );
        this.hostUrl = this.dashboardService.getHostURL();
        this.columnsConfig = this.reportData.columnsConfig;
        this.showExport = this.columnsConfig ? this.columnsConfig.showExport : false;

        if(this.hostUrl){            
            RESIZE_EVENT.subscribe(
                    (clientWidth: any) => {
                        console.log('on device width resize',clientWidth);
                        this.elWidth = clientWidth;
                        if( this.wdrSimpleGrid )
                        {
                            this.wdrSimpleGrid.webDataRocks.refresh();
                            this.zone.run(() => {
                                console.log( 'view refreshed' );
                            } );
                        }
                    }
            );
        } 

        /*
        this.report = {
            "dataSource": {
                "dataSourceType": "json",           
                "data": this.reportData['data']
            },
            "slice": {
                "rows": [
                    {
                        "uniqueName": "DR_NAME",
                        "sort": "desc"
                        
                    },
                    {
                        "uniqueName": "SC_CODE"
                    
                    },
                    {
                        "uniqueName": "SPECIALITY"
                        
                    },
                    {
                        "uniqueName": "LOCALITY"
                        
                    },
                    {
                        "uniqueName": "MGR_SUB"
                        
                    },
                    {
                        "uniqueName": "Measures"
                    }
                ],
                "flatOrder": [
                    "DR_NAME",   
                    "SC_CODE",                             
                    "LOCALITY",
                    "MGR_SUB",
                    "Country"
                ]
            }  
        };*/

    }

    onPivotReady(): void {
        console.log("WbrSimpleGridComponent [ready]", this.wdrSimpleGrid, this.reportData,  this.elWidth );
        //removeClass('fm-pivot-view','fm-ui-element');
    }
    
    customizeCellFunction (cell: any, data: any) { 
        console.log('customizeCellFunction :: ', cell, data);
        if (data.hierarchy && this.linkedColumns.indexOf(data.hierarchy.uniqueName) > -1 && data.type == "value") {
            var el = document.createElement( 'div' );
            el.innerHTML = cell.text;
            cell.text = "<span class='drill-down-link'>"+ el.innerText +"</span>";
        }
        if (data.type == "value") {
            if (data.rowIndex % 2 == 0) {
              cell.addClass("alter1");
            } else {
              cell.addClass("alter2");
            }
        }
        if(data.rowIndex == this.selectedRowIndex) {
            var idx1 = cell.classes.indexOf('alter1');
            var idx2 = cell.classes.indexOf('alter2');
            if(idx1 > -1){
                cell.classes.splice(idx1, 1);
            }
            if(idx2 > -1){
                cell.classes.splice(idx2, 1);
            }

            cell.classes.push('highlight-cell');
            this.selectedRowData[data.hierarchy.uniqueName.trim().toLowerCase()] = data.label;
        }
    }

    onReportComplete(): void {
        console.log('onReportComplete', this.reportData['data'], this.wdrSimpleGrid, this.columnsConfig );

        var reportConfig = {
           dataSource: {
                dataSourceType: "json",
                data: this.reportData['data']
           },
           options : {
                grid: {
                    type:  'flat',
                    showHeaders: false,
                    showFilter: false,
	                showGrandTotals : this.columnsConfig ? this.columnsConfig.showGrandTotals : 'off',
	                grandTotalsPosition : this.columnsConfig ? this.columnsConfig.grandTotalsPosition : 'top'
                },
                datePattern: this.columnsConfig ? this.columnsConfig.datePattern : "dd/MM/yy",
                configuratorButton : false, // As per KB sir, no need to parameterized.
                drillThrough: false,
                showCalculatedValuesButton: false,
                showDrillThroughConfigurator: false
           },
           /*
           formats: [
             {
               name: "",
               thousandsSeparator: ""
             }
           ],*/
           formats: this.columnsConfig ? this.columnsConfig.formats : [],
           columns: this.reportData.columns,
           tableSizes: {
               columns: this.reportData.columns,
           }
        };
        
        if( this.wdrSimpleGrid ) 
        {
            this.wdrSimpleGrid.webDataRocks.off("reportcomplete");
            console.log('simple reportConfig:::',reportConfig);
            this.wdrSimpleGrid.webDataRocks.setReport(reportConfig);
     
            console.log('simple pivotGrid:::',this.wdrSimpleGrid);   

        }
    }

    exportToExcel( ) {
      var options = {
         filename : 'report'
      }
      try
      {
          var fileName = this.reportData.title.replace(/[&\/\\|#,+()$~%.'":*?<>{}]/g, '');
          console.log('filename :: ', fileName);
          var params = {
              filename: '' + fileName,
              destinationType:'file',
              excelSheetName: 'Report',
              showFilters: true
          };
          console.log('exportToExcel', exportToFile);
          setTimeout( () =>{
              if( this.wdrSimpleGrid )
              {
                  this.wdrSimpleGrid.webDataRocks.exportTo('excel', params, exportToFile);
              }
          }, 2000); 
      }
      catch(e)
      {
          console.log('exportToExcel', e);
      }
      
    }
}
