import { Component, OnInit,Input, Output, EventEmitter } from '@angular/core';
import { ExcelService } from "../../../excel.service";
import { FILTER_DATA, DEEP_CLONE } from '../../composite.utils';

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

  constructor( private excelService:ExcelService ) { }
  @Input('ELEMENT_DATA') ELEMENT_DATA : any;
  @Input('parentData') configData : any;
  @Input('tableConfig') tableConfigData : any;
  @Output() onCustomCellAction: EventEmitter<any> = new EventEmitter();

  groupByRowCol = 1;

  isTableData = false;
  _tableData: any;
  _tableDataConfig: any = [];

  tableHeaderTitle: any = '';
  tableContentTitle: any = '';
  tableContentInitials: any = 'NA';
  exportFileName = '';
  exportToExcel = false;
  _sumofKeys: any[] = [];

  ngOnInit()
  {
      console.log('in bb custom table ',this.ELEMENT_DATA);
      console.log('in bb custom table :: configData ==> ',this.configData);

      if( this.tableConfigData ) {
          console.log('in bb custom table :: tableConfigData ==> ',this.tableConfigData);
          this.exportToExcel = this.tableConfigData['is_export'];
          this.exportFileName = this.tableConfigData['export_file_name'] || 'Export Data';
		  //Added by Sonam K on 2-MAR-20[To show total of column values at footer]
          if( this.tableConfigData['_sumofKeys'] ) {
              this._sumofKeys = this.tableConfigData['_sumofKeys'].split(",");
          }
      }

      this._tableData = DEEP_CLONE(this.ELEMENT_DATA);
      if( this.configData )
      {
        console.log('configData :: ',this.configData);
        this.applyConfiguration(this.configData);
      }
  }


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

    this.tableHeaderTitle = configData[titleHdrCol] || titleHdrCol || ''; //table_header : e.g. Product Group Details
    this.tableContentTitle = configData[titleContentCol] || titleContentCol || ''; //title_column : e.g. PRODUCT_DESCR

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

    var filterCols = configData['filter_columns'];
    if(filterCols)
    {
      this._tableDataConfig.push(this._tableData.shift());//0 => 2
      this._tableDataConfig.push(this._tableData.shift());//1 => 1
      this._tableDataConfig.push(this._tableData.shift());//2 => 0
      console.log('Before Filter data stringify ',JSON.stringify(this._tableData));

      filterCols = filterCols.split(',');
      console.log('in applyConfiguration ',filterCols);
      filterCols.map( (filterColumn: any) => {
        var filterValue = configData[filterColumn];
        console.log('in filter data for  ', filterColumn, '=', filterValue);
        this._tableData = FILTER_DATA(filterColumn, filterValue, this._tableData, 'strict');
      });
      //Added by Sainath T on 12-May-20 [To sort the data]
      //this.sortTableDataAlphabetically();

	  this.isTableData = (this._tableData && this._tableData.length > 0 );
      if( this.isTableData )
      {
        this._tableData.unshift(this._tableDataConfig.pop());//2 => 0
        this._tableData.unshift(this._tableDataConfig.pop());//1 => 1
        this._tableData.unshift(this._tableDataConfig.pop());//0 => 2
      }
      console.log('After Filter data stringify ',JSON.stringify(this._tableData));
      /*Added By Vikas Lagad on 24-02-20[build data for OT Connect details] Start*/
      var objName = configData['obj_name'];
      if( objName && objName == 'ot_connect_abm')
      {
          this._tableData = this.buildOTConnectDetails(this._tableData);
      }
      /*Added By Vikas Lagad on 24-02-20[build data for OT Connect details] Start*/
      console.log('After buildOTConnectDetails stringify ',JSON.stringify(this._tableData));
    }
    else
    {
        this.isTableData = (this._tableData && this._tableData.length > 2 );
        console.log('No Filter Columns & tableData available : ', this.isTableData);
    }
  }
/*
  FILTER_DATA(filterColumn, filterValue, data)
  {
      if(!filterColumn)
      {
          return data;
      }
      var sourceData = this.DEEP_CLONE(data);
      var filterData = sourceData.filter( (obj) => {
          //console.log('ngOnChanges filterCompObjects obj: ', obj);
          if(obj[filterColumn] === filterValue){
            return obj;
          }
      });

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

      return filterData;
  }

  DEEP_CLONE( data )
  {
      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);
  }

  buildOTConnectDetails( tableData: any )
  {
      //this._tableData = [];
      var  custConfProof = '',veriodDocId = '',sfsDocId = '';;
      console.log('Inside OT Connect Details :: ',tableData);
      for(var i = 0; i < tableData.length; i++)
      {
        if(tableData[i]["CUST_CONF"] && tableData[i]["CUST_CONF"] != '')
        {
            custConfProof = tableData[i]["CUST_CONF_PROOF"];
            console.log('custConfProof  :: ',custConfProof);
            if(custConfProof)
            {
                tableData[i]["CUST_CONF_html"] = tableData[i]["CUST_CONF"]  + "<br><span class='ot-link-css'>View attachment</span> <div class='"+custConfProof+"' id='"+custConfProof+"'></div>";
            }
        }
        if(tableData[i]["VERIO_F_METER"] && tableData[i]["VERIO_F_METER"] != '')
        {
            veriodDocId = tableData[i]["VERIO_DOC_ID"];
            console.log('veriodDocId  :: ',veriodDocId);
            if(veriodDocId && veriodDocId != '0')
            {
                tableData[i]["VERIO_F_METER_html"] = tableData[i]["VERIO_F_METER"]  + "<br><span class='ot-link-css'>View attachment</span> <div class='"+veriodDocId+"' id='"+veriodDocId+"'></div>";
            }
        }
        if(tableData[i]["SFS_METER"] && tableData[i]["SFS_METER"] != '')
        {

            sfsDocId = tableData[i]["SFS_DOC_ID"];
            console.log('sfsDocId  :: ',custConfProof);
            if(sfsDocId && sfsDocId != '0')
            {
                tableData[i]["SFS_METER_html"] = tableData[i]["SFS_METER"]  + "<br><span class='ot-link-css'>View attachment</span> <div class='"+sfsDocId+"' id='"+sfsDocId+"'></div>";
            }
        }
        //this._tableData.push(tableData[i]);
      }
      return tableData;
  }

  //Added by Sonam K on 28-Feb-20 [To convert json data into xsl sheet] START
  exportAsXLSX():void {
      console.log('Inside exportAsXLSX() :: _tableData ==> stringify ', JSON.stringify(this._tableData) );
      console.log('Inside exportAsXLSX() :: ELEMENT_DATA ==> stringify ', JSON.stringify(this.ELEMENT_DATA) );
      var jsonToExport: any = [];
      //var propertyData = this.rawData.splice(0,3);
      //this._tableData.splice(0,3);
      if ( this.ELEMENT_DATA && this.ELEMENT_DATA.length > 2 ) 
      {
          var columnKeys = this.ELEMENT_DATA[0]; //column names
          var displayColumnHeader = this.ELEMENT_DATA[1]; //display column headers
          var columnProperties = this.ELEMENT_DATA[2]; //column properties
          
          for ( var i = 0; i < this._tableData.length; i++ ) 
          {
              var obj = this._tableData[i];
              var data: any = {};
              for ( var j = 0; j < columnKeys.length; j++ ) 
              {
                  var colName = columnKeys[j];
                  var colValue = obj[colName];
                  var displayColHeader = displayColumnHeader[j];
                  data[displayColHeader] = colValue;//to change column headers as per displayNames in xsl
                  
                  if( i == 0 )
                  {
                      this.exportFileName = this.exportFileName.replace('<'+colName+'>', colValue);
                  }
              }
              jsonToExport.push( data );
          }
          console.log( 'jsonToExport ==> stringify ', JSON.stringify(jsonToExport) );

          this.excelService.exportAsExcelFile( jsonToExport, this.exportFileName );
      }

   }
  //Added by Sonam K on 28-Feb-20 [To convert json data into xsl sheet] END
    //Added by Sainath T on 12-May-20 [To sort the data] Start
    sortTableDataAlphabetically()
    {
      this._tableData.sort(sortAlphaNum);   
    }
    //Added by Sainath T on 12-May-20 [To sort the data] End
  
}

//Added by Sainath T on 12-May-20 [To sort the data] Start
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
 
function sortAlphaNum(a: any, b: any) {
  try
  {
	  var aA = a.DEALER_NAME.replace(reA, "");
	  var bA = b.DEALER_NAME.replace(reA, "");
	  if (aA === bA) 
	  {
	    var aN = parseInt(a.DEALER_NAME.replace(reN, ""), 10);
	    var bN = parseInt(b.DEALER_NAME.replace(reN, ""), 10);
	    return aN === bN ? 0 : aN > bN ? 1 : -1;
	  } else {
	    return aA > bA ? 1 : -1;
	  }
  }
  catch(e)
  {
  	console.log('Exception in sortAlpha...',e);
  }
}
//Added by Sainath T on 12-May-20 [To sort the data] End

