
declare var getBBHostURL: any;

declare var openComponentANG: any;

export function OPEN_DASHBOARD( dashboardName: any ) 
{
    openComponentANG(dashboardName, 'dashboard')
}


export function SUM( array: any, keystring: any, returnAsArray?: any ) : any {
    
    var keyList = keystring.split(',');
    keyList = keyList.map((key: any) => { return key.trim() });
    if( keystring.lastIndexOf(',') == keystring.length - 1 )
    {
        keyList.pop();
    }
    console.log('sum function : ',array);
    console.log('keyList : ',keyList);
    var sumArray: any = [];
    var sumValue = 0;
    var isArray = false;
    var returnArray = array.map(( objArr: any ) => {
        //console.log( objArr, objArr instanceof Array );
        if ( objArr instanceof Array ) {
            isArray = true;
            var finalObj = Object.assign({},objArr[0]);
            for(var key of keyList)
            {
                var totalSum = objArr.reduce( function( prev, cur ) {
                    return getIntValue(prev) + getIntValue(cur[key]);
                }, 0 );
                finalObj[key] = totalSum;
                objArr[0][key] = totalSum;
            }
            sumArray.push( finalObj );
        }
        else {
            sumValue = sumValue +getIntValue(objArr[keyList[0]]);
        }
        return objArr;
    } );
    if( returnAsArray ) {
        return returnArray;
    }
    else if ( isArray ) {
        return sumArray;
    }
    else {
        return sumValue;
    }
}


export function SORT_BY(array: any, key: any, col_type: any, order: any)
{
   var sortedArray = Object.assign([], array);
   if( sortedArray )
   {
       if(col_type=='number')
       {
           if(order=='ASC'){
               console.log('ASC');
               sortedArray.sort( function(a: any, b: any) {
                   return parseInt(a[key]) - parseInt(b[key]);
               }); 
           }
           else
            {
               console.log('DESC');
               sortedArray.sort( function(a: any, b: any) {
                   return parseInt(b[key]) - parseInt(a[key]);
               });                  
            }
       
       }
       else if(col_type=='date')
       {
           sortedArray.sort( function(a: any, b: any) {
               return parseInt(a[key]) - parseInt(b[key]);
           }); 
       
       }
       else
       {
           sortedArray.sort( function(a: any, b: any) {
               //return a[key] > b[key]
               return a[key].localeCompare(b[key], 'en', { numeric: true })
           });    
       }
   }
   //console.log(array, sortedArray);
   return sortedArray;
}


export function GROUP_BY_KEYS( dataList: any, keystring: any, returnType?: any ) 
{
    var result = dataList;
    if( keystring )
    {
        var keyList = keystring.split(',');
        keyList = keyList.map((key: any) => { return key.trim() });
        if( keystring.lastIndexOf(',') == keystring.length - 1 )
        {
            keyList.pop();
        }
        result = groupBy( returnType, dataList, function( item: any, keys: any ) {
            var kval = "";
            keys.map(( key: any, i: any ) => {
                kval += ( item[key].trim ? item[key].trim() : item[key] );
                if( (keys.length - 1) > i)
                {
                    kval +=  '_';
                }
            } );
            return kval;
        }, keyList );
    }
    return result;
}

function groupBy( returnType: any, array: any, f: any, kl: any ) {
    var groups: any = {};
    array.forEach( function( o: any ) {
        var group = JSON.stringify( f( o, kl ) );
        groups[group] = groups[group] || [];
        groups[group].push( o );
    } );
    if( returnType == "Object" ){
        return groups
    }
    else{ //Values
        return Object.keys( groups ).map( function( group ) {
            return groups[group];
        } )
    }
}

function getIntValue(value: any) 
{
    try {
        return parseInt(value);
    }
    catch ( e ) {
        return 0;
    }
}


export function RANK(component_data: any, key: any, filterkey: any, range: any, iscontinuous: any)
{
    var compDataLocal = Object.assign([], component_data);
    var rangeStart = 0;
    var rangeEnd = compDataLocal.length;
    if(range && range.indexOf(":") != -1)
    {
        var rangeArr = range.split(":");
        rangeStart = parseInt(rangeArr[0]);
        rangeEnd = parseInt(rangeArr[1]);
    }
    
    compDataLocal = SORT_BY(compDataLocal, key, 'number', 'DESC');
    
    if( iscontinuous )
    {
        compDataLocal = compDataLocal.map((d: any, i: any)=>{
            d['rank'] = ( i + 1 );
            return d;
        });
    }
    else
    {
        var rank = 0, prevrank = 0, prev: any = {};
        compDataLocal = compDataLocal.map( (curr: any, i: any) => {
            prevrank = prevrank + 1;
            if(prev[key] ==  curr[key]) 
            {       
                curr['rank'] = rank;
            }
            else
            {
                rank = prevrank;
                prev = curr;
                curr['rank'] = rank;
            }
            return curr;
        });
    }
    
    
    var empCode = localStorage.getItem('userName');
    var currentEmp = compDataLocal.filter((d: any)=>{
        if( d[filterkey].trim() === empCode )
        return d;
    });
    console.log('Inside RANK ...', empCode, currentEmp);

    var currentidx = compDataLocal.indexOf(currentEmp[0])
    var firstIdx = (currentidx - rangeStart);
    var lastIdx = (currentidx + rangeEnd);
    
    console.log('Inside RANK ...', currentidx, rangeStart, rangeEnd, firstIdx, lastIdx);
    var rankRangeData: any = [];
    for( var idx = firstIdx; idx <= lastIdx; idx++ )
    {
        if( idx == -1 || idx > compDataLocal.length ){
            rankRangeData.push( {} );
        }
        else if( idx == currentidx ){
            compDataLocal[idx]['image'] = 'USER:' + empCode;//getUserImage(empCode);
            rankRangeData.push(compDataLocal[idx]);
        }
        else {
            compDataLocal[idx]['image'] = 'USER_STATIC'; //getSVGImage();
            rankRangeData.push(compDataLocal[idx]);
        }
    }
    console.log('Inside RANK ...', rankRangeData);
    return rankRangeData;
}


export function PREPARE_COMPOSITE_OBJECTS(component_data: any, component_config: any)
{
    var compositeObjects: any = [];
    var compDataLocal: any = [];
    try{
        compDataLocal = JSON.parse(JSON.stringify(component_data));
    }
    catch(e){
        compDataLocal = Object.assign([], component_data);
    }
    
    console.log('Inside PREPARE_COMPOSITE_OBJECTS *** ...', component_config);
    console.log('Inside PREPARE_COMPOSITE_compDataLocal ', compDataLocal);
    
    try
    {
        var detailObject = component_config.detailModel ? component_config.detailModel : {};
        var summaryObject = component_config.summaryModel;
        console.log(' summaryObject  ' , summaryObject);
		var selectedIndex = component_config.selected_detail;
		selectedIndex = isNaN(selectedIndex) ? -1 : selectedIndex;
        if( component_config.component_type === 'BANNER_CARD' )
        {
            compDataLocal = compDataLocal.map( (data: any) => {
                var mergeData = Object.assign(data, detailObject);
                mergeData = updateImage(mergeData);
                return mergeData;
            });

            var cardObj: any = {}
            cardObj['data'] = compDataLocal;
            
            var compObj: any = {};
            compObj['cards'] = [];
            compObj['cards'].push(cardObj)
            
            compositeObjects.push(compObj);
        }
        else if( component_config.component_type === 'SIMPLE_CARD_5' || component_config.component_type === 'SIMPLE_CARD_4' )
        {
        
         	 console.log(' iside the SIMPLE_CARD_5  compDataLocal[0]', compDataLocal);
             console.log(' iside the SIMPLE_CARD_5  *****[0]', component_config.detailModel.chartConfig.datasets);
            
          	var datadrCount = [] ;
          	var dataprCount = [] ;
          	if ( component_config.detailModel.chartConfig.datasets )
          	{
          	  console.log(' iside the SIMPLE_CARD_5');
          	  var dataset =  component_config.detailModel.chartConfig.datasets;
          	  var columnNameDr = dataset[0].linecolumnName;
              console.log('component_config columnNameDr' , columnNameDr);
              var columnNamePr = dataset[1].linecolumnName;
              console.log('component_config columnNamePr' , columnNamePr);
          	 


            //     var datadrCountArray = [];
            //     var dataprCountArray = [];
                 
            //     for ( var i =0 ; i < compDataLocal.length; i++)
            //     {

            //          if ( typeof compDataLocal[i][columnName] === 'string' )
            //          {
            //              var temp = JSON.parse(compDataLocal[i][columnName]);
            //              datadrCountArray.push(temp); 
            //          }

            //           if ( typeof compDataLocal[0][columnNamePr] === 'string' )
            //          {
            //              var temp = JSON.parse(compDataLocal[i][columnNamePr]);
            //              dataprCountArray.push(temp); 
            //          }

                     
            //     }
          	//    console.log('component_configdataprCountArray' , dataprCountArray);
            //    console.log('component_config datadrCountArray' , datadrCountArray);
          	//   component_config.detailModel.chartConfig.datasets[1]['data'] = dataprCount;
          	  
          	//   console.log('component_config dataprCount changes' , dataprCount);

              console.log('component_config before component_config passed ' , component_config.detailModel);

              // Added bY Nilesh y coornate with the dynamic lable 

              var lables =  component_config.detailModel.chartConfig.ylabels;
              console.log('component_config lables' , lables);
             
                var lablesValue = compDataLocal[0][lables];
                console.log('component_config lablesValue' , lablesValue);
                 console.log('component_config lablesValue' , typeof lablesValue);
                if ( typeof lablesValue === 'string' )
                 {
                     lablesValue  = eval(lablesValue);
                }
                console.log('component_config nil lablesValue' , lablesValue);
                component_config.detailModel.chartConfig['labels'] = lablesValue;
                console.log('component_config lablesValue after ' , lablesValue);

             


             var compObj: any = {};
              compObj['cards'] = [];

                compObj['cards'] = compDataLocal.map( (data: any) => {

                     console.log('data[columnNameDr]' ,data[columnNameDr]);
                     console.log('data[columnNamePr]' ,data[columnNamePr]);
                    console.log('data[selectedIndex]' ,selectedIndex);
                     var lablesValue = data[lables];
                     console.log('component_config lablesValue' , lablesValue);
                    
                     datadrCount =  data[columnNameDr];

                     if ( typeof datadrCount === 'string' )
                     {
                        datadrCount  = JSON.parse(datadrCount);
                     }	  
        
          	        dataprCount =   data[columnNamePr];
                    if ( typeof dataprCount === 'string' )
                    {
                        dataprCount  = JSON.parse(dataprCount);
                    }

                    if ( typeof lablesValue === 'string' )
                    {
                        lablesValue  = eval(lablesValue);
                    }       
                    console.log('component_config datadrCount' , datadrCount);
                    console.log('component_config dataprCount' , dataprCount);
                    console.log('component_config lablesValue::::' , lablesValue);

                    component_config.detailModel.chartConfig['labels'] = lablesValue;
                    component_config.detailModel.chartConfig.datasets[0]['data'] = datadrCount;
                    component_config.detailModel.chartConfig.datasets[1]['data'] = dataprCount;
                    
                   var tempData = JSON.stringify(component_config);
                   var tempDataVal =  JSON.parse(tempData);
                   console.log('component_config tempDataVal ' , tempDataVal);
                    

                    console.log('component_config for loop  component_config passed ' , tempDataVal.detailModel);
                    console.log('component_config for loop json   component_config passed ' , JSON.stringify(tempDataVal.detailModel));

                    var mergeData = Object.assign(data, tempDataVal.detailModel);

                    

                    mergeData = updateImage(mergeData);
                    console.log('component_config after component_config ' , mergeData);
                    mergeData = formatData(mergeData, component_config);
                    console.log('component_config after component_config mergeData ' , mergeData);
                    console.log('component_config after json strigfy mergeData ' , JSON.stringify(mergeData));

                   
                    console.log('after det value  after json strigfy mergeData ' , JSON.stringify(mergeData));


                    return mergeData;
                });
                

            console.log('component_config after component_config passed ' , component_config);

            console.log('component_config compObj ' , JSON.stringify(compObj));

            console.log('before  for loop  ' ,  compDataLocal );

            //  for (var i = 0 ; i < compDataLocal.length && compDataLocal.length > 1 ; i++ )
            //  {

            //      console.log(' inside the for looo[ ] ' , compDataLocal[i]);
            //      console.log(' inside the columnName ' , compDataLocal[i][columnName]);
            //      console.log(' inside the  columnNamePr ' , compDataLocal[i][columnNamePr]);
            //      var configModel = component_config.detailModel ;
            //      console.log(' after for loop configModel ' , configModel);

            //      Object.assign( compDataLocal[i], configModel)
            //      //  var mergeData = Object.assign(data, component_config.detailModel);
            //      compDataLocal[i].chartConfig.datasets[0]['data'] = compDataLocal[i][columnName];
            //      compDataLocal[i].chartConfig.datasets[1]['data'] = compDataLocal[i][columnNamePr];

            //       console.log(' after in  for loop changes ' , JSON.stringify(compDataLocal[i]));
            //       compObj['cards'].push( compDataLocal[i]) ;

            //     console.log(' after in  for loop  compObj[cards] ' , JSON.stringify( compObj['cards']));
            //     console.log(' after in  for loop  compObj[cards] ' , compObj['cards']);


            //  }
            console.log(' after for loop ' , JSON.stringify(compObj));
           
                           console.log(' after for after loop  ' , selectedIndex);

              if( selectedIndex != -1 )
			  {
						var toBeSelect = compObj['cards'][selectedIndex];
						toBeSelect['selected'] = true;
			  }
             console.log(' after for loop ' , JSON.stringify(compObj));
            console.log(' after for loop ' , (compObj));
                        compositeObjects.push(compObj);

         }
            
        }
        else
        {
            if ( compDataLocal[0] instanceof Array )
            {
                console.log(' compDataLocal[0] ' , compDataLocal[0]);
                compositeObjects = compDataLocal.map( (data: any) => {
                    var compObj: any = {};
                    
                    //compObj['title'] = data[0][detailObject.title_column];
                    var titleColumn = detailObject.title_column;
                    if( detailObject.header_column )
                    {
                        titleColumn = detailObject.header_column;
                    }
                    compObj['title'] = data[0][titleColumn];
                    compObj['cards'] = data.map( (d: any) =>{
                        var mergeData = Object.assign(d, detailObject);
                        mergeData = updateImage(mergeData);
                        mergeData = formatData(mergeData, component_config);
                        return mergeData;
                    }) ;
					if( selectedIndex != -1 )
					{
						var toBeSelect = compObj['cards'][selectedIndex];
						toBeSelect['selected'] = true;
					}
                    return compObj;
                });
            }
            else
            {
                var compObj: any = {};
                compObj['cards'] = compDataLocal.map( (data: any) => {
                    var mergeData = Object.assign(data, detailObject);
                    mergeData = updateImage(mergeData);
                    mergeData = formatData(mergeData, component_config);
                    return mergeData;
                });
                //unshift/push - add an element to the beginning/end of an array
                //shift/pop - remove and return the first/last element of an array
                if(summaryObject)
                {
                	//Chnaged by Prasad on 01/06/2020 [to display summary data in first card] START
                    /*var copyDataObject = compObj['cards'][0];
                    if(copyDataObject && summaryObject.copykeys)
                    {
                        var copyKeysDataArr = summaryObject.copykeys.split(',');
                        copyKeysDataArr.map( (key) => {
                            summaryObject[key] = copyDataObject[key];
                        });
                    }*/
                    try 
                    {
                        var isDataCopied = false;
                        if( summaryObject['_OBJECT_KEY'] && summaryObject.copykeys )
                        {
                            var copyKeys = summaryObject.copykeys;
                            console.log('Inside copyKeys ...', copyKeys);
                            var objectKey = summaryObject['_OBJECT_KEY'];
                            console.log('Inside objectKey ...', objectKey);
                            var objectKeyValue = summaryObject[objectKey];
                            console.log('Inside objectKeyValue 1...', objectKeyValue);
                            if ( ! objectKeyValue || objectKeyValue === 'null' )
                            {
                                updateStorageValue( summaryObject );
                                objectKeyValue = summaryObject[objectKey];
                                console.log('Inside objectKeyValue 2...', objectKeyValue);

                                if ( ! objectKeyValue || objectKeyValue === 'null' )
                                {
                                    var storageKey = summaryObject['_STORAGE_KEY'];
                                    console.log('Inside storageKey ...', storageKey);
                                    var copyDataObject = compObj['cards'][0];
                                    if( copyDataObject )
                                    {
                                        objectKeyValue = copyDataObject[storageKey];
                                    }
                                    console.log('Inside objectKeyValue 3...', objectKeyValue);
                                }
                            }
                            console.log('Inside objectKeyValue ...', objectKeyValue);
                            var compObjLen = (compObj['cards']).length;
                            console.log('Inside sumKeys ...compObj', (compObj['cards']), compObjLen);
                            for( var compIdx = 0; compIdx < compObjLen; compIdx++ )
                            {
                                var copyDataObject = compObj['cards'][compIdx];
                                console.log('copyDataObject --->', copyDataObject);
                                var cardKeyValue = "";
                                if ( copyDataObject && copyDataObject[objectKey] )
                                {
                                    cardKeyValue = copyDataObject[objectKey];
                                    console.log('cardKeyValue --->', cardKeyValue);
                                    if ( cardKeyValue == objectKeyValue && copyKeys )
                                    {
                                        var copyKeysDataArr = copyKeys.split(',');
                                        copyKeysDataArr.map( (key: any) => {
                                            summaryObject[key] = copyDataObject[key];
                                        });
                                        (compObj['cards']).splice(compIdx, 1);
                                        isDataCopied = true;
                                        break;
                                    }
                                }
                            }
                        }
                        console.log('isDataCopied --->', isDataCopied);
                        if ( ! isDataCopied )
                        {
                            var copyDataObject = compObj['cards'][0];
                            if(copyDataObject && summaryObject.copykeys)
                            {
                                var copyKeysDataArr = summaryObject.copykeys.split(',');
                                copyKeysDataArr.map( (key: any) => {
                                    summaryObject[key] = copyDataObject[key];
                                });
                            }
                        }
                    }
                    catch(e)
                    {
                        console.log('Inside catch objectKeys ', e);
                    }

                    try 
                    {
                        var compObjLen = (compObj['cards']).length;
                        console.log('Inside avgKeys ...compObj', (compObj['cards']), compObjLen);
                        for( var compIdx = 0; compIdx < compObjLen; compIdx++ )
                        {
                            var copyDataObject = compObj['cards'][compIdx];
                            console.log('copyDataObject --->', copyDataObject);
                            if ( copyDataObject && summaryObject.avgkeys )
                            {
                                var avgkeysDataArr = summaryObject.avgkeys.split(',');
                                console.log('avgkeysDataArr --->', avgkeysDataArr);
                                avgkeysDataArr.map( (key: any) => {

                                    var colval = isNaN(summaryObject[key]) ? 0 : summaryObject[key];
                                    console.log('colval --->', colval);
                                    summaryObject[key] = (colval + copyDataObject[key]);
                                });
                            }
                        }

                        if ( compObjLen > 0 )
                        {
                            if ( summaryObject.avgkeys )
                            {
                                var avgkeysDataArr = summaryObject.avgkeys.split(',');
                                console.log('avgkeysDataArr --->', avgkeysDataArr);
                                avgkeysDataArr.map( (key: any) => {

                                    var colval = isNaN(summaryObject[key]) ? 0 : summaryObject[key];
                                    console.log('colval --->', colval);
                                    summaryObject[key] = Math.round(colval / compObjLen);
                                });
                            }
                        }
                    }
                    catch(e)
                    {
                        console.log('Inside catch avgkeys ', e);
                    }

                    try 
                    {
                        var compObjLen = (compObj['cards']).length;
                        console.log('Inside sumKeys ...compObj', (compObj['cards']), compObjLen);
                        for( var compIdx = 0; compIdx < compObjLen; compIdx++ )
                        {
                            var copyDataObject = compObj['cards'][compIdx];
                            console.log('copyDataObject --->', copyDataObject);
                            if ( copyDataObject && summaryObject.sumkeys )
                            {
                                var sumKeysDataArr = summaryObject.sumkeys.split(',');
                                console.log('sumKeysDataArr --->', sumKeysDataArr);
                                sumKeysDataArr.map( (key: any) => {

                                    var colval = isNaN(summaryObject[key]) ? 0 : summaryObject[key];
                                    console.log('colval --->', colval);
                                    summaryObject[key] = (colval + copyDataObject[key]);
                                });
                            }
                        }
                    }
                    catch(e)
                    {
                        console.log('Inside catch sumkeys ', e);
                    }
                    //Chnaged by Prasad on 01/06/2020 [to display summary data in first card] END
                    summaryObject['IS_SUMMARY'] = 'true';
                    console.log('Inside PREPARE_COMPOSITE_OBJECTS ...summaryObject', summaryObject);
                    compObj['cards'].unshift(summaryObject); 
                }
				else if( selectedIndex != -1 )
				{
					var toBeSelect = compObj['cards'][selectedIndex];
					toBeSelect['selected'] = true;
				}
                compositeObjects.push(compObj);
            }
        }
    }
    catch(e)
    {
        
    }
    console.log('Inside PREPARE_COMPOSITE_OBJECTS ...', compositeObjects);

    return compositeObjects;
}

function updateImage(data: any){
    
    console.log('Inside updateImage data : ', data);
    var imageSrc = data['image'];
    var imageColumn = data['image_column'];
    var thumbObj = data['thumb_obj'];
    console.log('Inside updateImage imageSrc & imageColumn & thumbObj: ', imageSrc, imageColumn, thumbObj);
    if( !imageSrc && imageColumn )
    {
        if( imageColumn.indexOf('USER:') != -1 )
        {
            var fieldName = imageColumn.replace('USER:', '');
            var fieldValue =  data[fieldName];
            data['image'] = getUserImage(fieldValue);
        }
        else if ( thumbObj )
        {
            var fieldValue =  data[imageColumn];
            data['image'] = getResourceImage(thumbObj, fieldValue);
        }
        else
        {
            data['image'] = data[imageColumn];
        }
    }
    else if( imageSrc === 'USER_STATIC' )
    {
        data['image'] = getSVGImage('avatar.svg');
    }
    else if( imageSrc && imageSrc.indexOf('USER:') != -1 )
    {
        var empCode = imageSrc.replace('USER:', '');
        data['image'] = getUserImage(empCode);
    }
    
    var altImageColumn = data['alt_image_column'];
    if(altImageColumn)
    {
        data['alt_image'] = getSVGImage(data[altImageColumn]);
    }
    return data;
}

export function getUserImage(userCode: any){
    var userImage = getBBHostURL() + "/ibase/resource/images/users/" + (userCode ? userCode.trim() : "default" )+ ".png";
    return userImage;
}

export function getResourceImage(thumbObj: any, thumbImg: any){
    var resourceImage = getBBHostURL() + "/ibase/resource/"+thumbObj+"/" + (thumbImg ? thumbImg.trim() : "default" )+ ".png";
    return resourceImage;
}

function getSVGImage(imgName: any){
    return "dashboard/assets/images/svg/" + imgName;
}


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


export function FILTER_DATA(filterColumn: any, filterValue: any, data: any, filterMode?: any)
{
    if(!filterColumn)
    {
        return data;
    }
    var filterValues = filterValue.split(',');
    var sourceData = DEEP_CLONE(data);
    var filterData = sourceData.filter( (obj: any) => {
        //console.log('ngOnChanges filterCompObjects obj: ', obj);
        var objValue = obj[filterColumn];
        //if(obj[filterColumn] === filterValue){
        if(objValue === filterValue || filterValues.includes(objValue)){
           return obj;
        }
    });
    if(filterData.length == 0 && filterMode != 'strict'){
        return sourceData;
    }
    else{
        return filterData;
    }
}


export function AVERAGE( array: any, keystring: any, returnAsArray?: any ) : any {
    
    var keyList = keystring.split(',');
    keyList = keyList.map((key: any) => { return key.trim() });
    if( keystring.lastIndexOf(',') == keystring.length - 1 )
    {
        keyList.pop();
    }
    console.log('avg function : ',array);
    console.log('keyList : ',keyList);
    var avgArray: any = [];
    var avgValue = 0;
    var isArray = false;
    var returnArray = array.map(( objArr: any ) => {
        //console.log( objArr, objArr instanceof Array );
        if ( objArr instanceof Array ) {
            isArray = true;
            var finalObj = Object.assign({},objArr[0]);
            for(var key of keyList)
            {
                var _avgValue = 0;
                var totalSum = objArr.reduce( function( prev, cur ) {
                    return getIntValue(prev) + getIntValue(cur[key]);
                }, 0 );
                if( objArr.length > 0 )
                {
                    _avgValue = getIntValue(totalSum / objArr.length);
                }
                finalObj[key] = _avgValue;
                objArr[0][key] = _avgValue;
            }
            avgArray.push( finalObj );
        }
        else {
            avgValue = avgValue + getIntValue(objArr[keyList[0]]);
        }
        return objArr;
    } );
    if( returnAsArray ){
        return returnArray;
    }
    if ( isArray ) {
        return avgArray;
    }
    else {
        return avgValue;
    }
}

export function UNIQUE( array: any ) : any 
{
    console.log('UNIQUE function : ',array);
    var uniqueArray: any = [];
    var isArray = false;
    array.map(( objArr: any ) => {
        //console.log( objArr, objArr instanceof Array );
        if ( objArr instanceof Array ) 
        {
            isArray = true;
            var uniqueObj = Object.assign({},objArr[0]);
            uniqueArray.push( uniqueObj );
        }

    });
    return ( uniqueArray.length > 0 ) ? uniqueArray : array ;
}

export function UPDATE_TAB_DATA(component_data: any, tabConfig: any)
{
    var compDataLocal: any = [];
    try
    {
        compDataLocal = JSON.parse(JSON.stringify(component_data));
    }
    catch(e)
    {
        compDataLocal = Object.assign([], component_data);
    }
    
    console.log('Inside UPDATE_TAB_DATA ...', tabConfig, compDataLocal);
    try
    {
        var _tabs = tabConfig.tabs;
        var scaleObject =  tabConfig.tabChartScales;
        var tabChartConfig = tabConfig.tabChartConfig;
        console.log('Inside UPDATE_TAB_DATA ... _tabs', _tabs, scaleObject);
        console.log('Inside tabChartConfig ... _tabs', _tabs, tabChartConfig);


       /* _tabs = _tabs.map((tab => {

            
           
            console.log(' Inside the ', _tabs);


            var _chartConfig = tab.chartConfig;
            
            if ( _chartConfig !== undefined && _chartConfig !== null )
            {

                    console.log(' Inside the _chartConfig', _chartConfig);
            if(tabChartConfig)
            {
                _chartConfig = Object.assign(_chartConfig, tabChartConfig);
            }
            
            var options = _chartConfig['options'];
            var dataColumn = _chartConfig['y_column'];
            var labelColumn = _chartConfig['x_column'];
            var _datasets = DEEP_CLONE(_chartConfig['datasets']) || [];
             console.log(' Inside the _datasets', _datasets);
            console.log( '_chartConfig', dataColumn, labelColumn, _datasets);
            
            //Summary Object Processing Starts
            var _summary = tab.summary; 
            if(_summary)
            {
                var summaryData = FILTER_DATA_BY_EXPR(_summary.filterExpr, compDataLocal);
                var _summaryData = summaryData[0];
                if( _summaryData )
                {
                    _summary['chartdata'] = _summaryData[_summary.summary_data_column];
                    _summary[_summary.summary_target_column] = _summaryData[_summary.summary_target_column];
                    _summary['summary_info_text'] = _summaryData[_summary.summary_info_column];
                    _summary['summary_subinfo_text'] = _summaryData[_summary.summary_subinfo_column];
                }
            }
            console.log( '_summary', _summary);
            //Summary Object Processing Ends
            
            // Dataset and Labels creation - Starts
            var _filterExpr = tab.filterExpr;
            var tabData = FILTER_DATA_BY_EXPR(_filterExpr, compDataLocal);
            console.log( '_filterExpr', _filterExpr, tabData);
            
            var dataArr = tabData.map((_tabData => {
                return _tabData[dataColumn];
            }) );
            
            var labelsArr = tabData.map((_tabData => {
                return _tabData[labelColumn];
            }) );
            
             //var visit_count_column;
            //var visit_info_column ;
            var visitCountArr;
            var visitInfoArr;
            if( _chartConfig['visit_count_column'] ) {
                var visit_count_column = _chartConfig['visit_count_column'];
                console.log('visit_count_column >>', visit_count_column);
                visitCountArr = tabData.map((_tabData => {
                    if( _tabData['DATA_GRP'] == "MTD_DETAIL" ) {
                        console.log( '!!!!!!!!', _tabData[visit_count_column] );
                        console.log(typeof( _tabData[visit_count_column] ));
                        var _data_ = _tabData[visit_count_column];
                        if( typeof(_data_) === 'string' ) {
                            console.log('%%%%%');
                            _data_ = JSON.parse(_data_);
                        }
                        console.log('****', _data_, typeof(_data_));
                        return _data_;
                    }
                }) );
            }
            
            if( _chartConfig['visit_info_column'] ) {
                var visit_info_column = _chartConfig['visit_info_column']; 
                console.log('visit_info_column >>', visit_info_column);
                visitInfoArr = tabData.map((_tabData => {
                    if( _tabData['DATA_GRP'] == "MTD_DETAIL" ) {
                        console.log('######' , _tabData[visit_info_column]);
                        console.log( typeof( _tabData[visit_info_column] ) );
                        var _data_ = _tabData[visit_info_column];
                        if( typeof(_data_) === 'string' ) {
                            console.log('&&&&');
                            _data_ = JSON.parse(_data_);
                        }
                        console.log('^^^^', _data_, typeof(_data_));
                        return _data_;
                    }
                }) );
            }
            
            var _dataset = {
              'data' : dataArr,
              'labels' : labelsArr,
              'dataSource' : tab.title,
              'visitCount' : visitCountArr,
              'visitInfo' : visitInfoArr
            };
            console.log( '_dataset', _dataset);
            
            if(_datasets.length == 0)
            {
                tab['datasets'] = [_dataset];
            }
            else
            {
                _datasets = _datasets.map( (dataset)=> {
                    return Object.assign(dataset, _dataset);
                });
                tab['datasets'] = _datasets;
            }
            tab['labels'] = labelsArr;
            // Dataset and Labels creation - Ends
            
            
            // Add ScaleLabel in options - Starts
            var xColumnLbl = _chartConfig['x_column_label'];
            if( xColumnLbl && scaleObject )
            {
                var xAxis = scaleObject.xAxes[0];
                var scaleLabel = {};
                scaleLabel['display'] = true;
                scaleLabel['labelString'] = xColumnLbl;
                
                xAxis['scaleLabel'] = scaleLabel;
            }

            var yColumnLbl = _chartConfig['y_column_label'];
            if( yColumnLbl && scaleObject )
            {
                var yAxis = scaleObject.yAxes[0];
                var scaleLabel = {};
                scaleLabel['display'] = true;
                scaleLabel['labelString'] = yColumnLbl;
                
                yAxis['scaleLabel'] = scaleLabel;
            }
            if(scaleObject)
            {
                options['scales'] = scaleObject;
            }
            // Add ScaleLabel in options - Ends
            }
            else
            {
                console.log(' Inside the Card of tab ');

                var _filterExpr = tab.filterExpr;
                var tabData = FILTER_DATA_BY_EXPR(_filterExpr, compDataLocal);
                console.log( '_filterExpr', _filterExpr, tabData);
            
                tab['data']['detailModel'] = tabData;
            
            }  
            console.log( 'tab Before Return ', tab); 
            return tab;
            
        }));*/
        _tabs = _tabs.map((tab: any)=> {

            
           
            console.log(' Inside the ', _tabs);


            var _chartConfig = tab.chartConfig;
            
            if ( _chartConfig !== undefined && _chartConfig !== null )
            {

                    console.log(' Inside the _chartConfig', _chartConfig);
            if(tabChartConfig)
            {
                _chartConfig = Object.assign(_chartConfig, tabChartConfig);
            }
            
            var options = _chartConfig['options'];
            var dataColumn = _chartConfig['y_column'];
            var labelColumn = _chartConfig['x_column'];
            var _datasets = DEEP_CLONE(_chartConfig['datasets']) || [];
             console.log(' Inside the _datasets', _datasets);
            console.log( '_chartConfig', dataColumn, labelColumn, _datasets);
            
            //Summary Object Processing Starts
            var _summary = tab.summary; 
            if(_summary)
            {
                var summaryData = FILTER_DATA_BY_EXPR(_summary.filterExpr, compDataLocal);
                var _summaryData = summaryData[0];
                if( _summaryData )
                {
                    _summary['chartdata'] = _summaryData[_summary.summary_data_column];
                    _summary[_summary.summary_target_column] = _summaryData[_summary.summary_target_column];
                    _summary['summary_info_text'] = _summaryData[_summary.summary_info_column];
                    _summary['summary_subinfo_text'] = _summaryData[_summary.summary_subinfo_column];
                }
            }
            console.log( '_summary', _summary);
            //Summary Object Processing Ends
            
            // Dataset and Labels creation - Starts
            var _filterExpr = tab.filterExpr;
            var tabData = FILTER_DATA_BY_EXPR(_filterExpr, compDataLocal);
            console.log( '_filterExpr', _filterExpr, tabData);
            
            var dataArr = tabData.map((_tabData: any) => {
                return _tabData[dataColumn];
            } );
            
            var labelsArr = tabData.map((_tabData: any) => {
                return _tabData[labelColumn];
            } );
            
             //var visit_count_column;
            //var visit_info_column ;
            var visitCountArr;
            var visitInfoArr;
            if( _chartConfig['visit_count_column'] ) {
                var visit_count_column = _chartConfig['visit_count_column'];
                console.log('visit_count_column >>', visit_count_column);
                visitCountArr = tabData.map((_tabData: any) => {
                    if( _tabData['DATA_GRP'] == "MTD_DETAIL" ) {
                        console.log( '!!!!!!!!', _tabData[visit_count_column] );
                        console.log(typeof( _tabData[visit_count_column] ));
                        var _data_ = _tabData[visit_count_column];
                        if( typeof(_data_) === 'string' ) {
                            console.log('%%%%%');
                            _data_ = JSON.parse(_data_);
                        }
                        console.log('****', _data_, typeof(_data_));
                        return _data_;
                    }
                } );
            }
            
            if( _chartConfig['visit_info_column'] ) {
                var visit_info_column = _chartConfig['visit_info_column']; 
                console.log('visit_info_column >>', visit_info_column);
                visitInfoArr = tabData.map((_tabData: any) => {
                    if( _tabData['DATA_GRP'] == "MTD_DETAIL" ) {
                        console.log('######' , _tabData[visit_info_column]);
                        console.log( typeof( _tabData[visit_info_column] ) );
                        var _data_ = _tabData[visit_info_column];
                        if( typeof(_data_) === 'string' ) {
                            console.log('&&&&');
                            _data_ = JSON.parse(_data_);
                        }
                        console.log('^^^^', _data_, typeof(_data_));
                        return _data_;
                    }
                } );
            }
            
            var _dataset = {
              'data' : dataArr,
              'labels' : labelsArr,
              'dataSource' : tab.title,
              'visitCount' : visitCountArr,
              'visitInfo' : visitInfoArr
            };
            console.log( '_dataset', _dataset);
            
            if(_datasets.length == 0)
            {
                tab['datasets'] = [_dataset];
            }
            else
            {
                _datasets = _datasets.map( (dataset: any)=> {
                    return Object.assign(dataset, _dataset);
                });
                tab['datasets'] = _datasets;
            }
            tab['labels'] = labelsArr;
            // Dataset and Labels creation - Ends
            
            
            // Add ScaleLabel in options - Starts
            var xColumnLbl = _chartConfig['x_column_label'];
            if( xColumnLbl && scaleObject )
            {
                var xAxis = scaleObject.xAxes[0];
                var scaleLabel: any = {};
                scaleLabel['display'] = true;
                scaleLabel['labelString'] = xColumnLbl;
                
                xAxis['scaleLabel'] = scaleLabel;
            }

            var yColumnLbl = _chartConfig['y_column_label'];
            if( yColumnLbl && scaleObject )
            {
                var yAxis = scaleObject.yAxes[0];
                var scaleLabel: any = {};
                scaleLabel['display'] = true;
                scaleLabel['labelString'] = yColumnLbl;
                
                yAxis['scaleLabel'] = scaleLabel;
            }
            if(scaleObject)
            {
                options['scales'] = scaleObject;
            }
            // Add ScaleLabel in options - Ends
            }
            else
            {
                console.log(' Inside the Card of tab ');

                var _filterExpr = tab.filterExpr;
                var tabData = FILTER_DATA_BY_EXPR(_filterExpr, compDataLocal);
                console.log( '_filterExpr', _filterExpr, tabData);
            
                tab['data']['detailModel'] = tabData;
            
            }  
            console.log( 'tab Before Return ', tab); 
            return tab;
            
        });
    
        console.log( '_tabs', _tabs);
    }
    catch(e)
    {
          console.log('UPDATE_TAB_DATA :: exception ... ',e);
    }
    console.log('Inside UPDATE_TAB_DATA ...', tabConfig);

    return tabConfig;
}

export function FILTER_DATA_BY_EXPR(filterExpression: any, data: any)
{
    if(!filterExpression)
    {
        return data;
    }
    var sourceData = DEEP_CLONE(data);
    var filterData = sourceData.filter( (data: any) => {
        if(eval(filterExpression))
        {
           return data;
        }
    });
    if(filterData.length == 0){
        return sourceData;
    }
    else{
        return filterData;
    }
}

//Added by Prajyot R. on 24-MAR-2020 [To format data as per formatExpression and formatCondition] Starts
function formatData(data: any, component_config: any)
{
    var dataFormats = component_config.dataFormats;
    console.log('Inside formatData data : ', JSON.stringify(data), dataFormats);
    if( dataFormats )
    {
        dataFormats.map( (dataFormat: any) => {
            if(dataFormat && eval(dataFormat.formatCondition) )
            {
                var formatExpressions = dataFormat.formatExpressions;
                if( formatExpressions )
                {
                    formatExpressions.map((formatExpression: any) => {
                        eval(formatExpression);
                    });
                }
            }
        });
    }
    console.log('Inside formatData data : ', JSON.stringify(data));
    return data;
}
//Added by Prajyot R. on 24-MAR-2020 [To format data as per formatExpression and formatCondition] Ends

//Chnaged by Prasad on 01/06/2020 [to set storage value] START
function updateStorageValue( card: any )
{
    try 
    {
        console.log('updateStorageValue :: card ... ',card);
        if ( card )
        {
            var objectKey = card['_OBJECT_KEY'];
            var storageKey = card['_STORAGE_KEY'];
            console.log('updateStorageValue :: objectKey ['+ objectKey +'], storageKey ['+ storageKey +']');
            var storageValue = localStorage.getItem(storageKey) + '';
            console.log('updateStorageValue storageValue ... ', storageValue);
            if( storageValue === 'null' )
            {
                storageValue = card[storageKey];
                console.log('updateStorageValue nullcond storageValue ... ', storageValue);
            }
            storageValue = storageValue.padEnd(10);// Temporary padding Space 
            console.log('storageValue ... ', storageValue);
            card[objectKey] = storageValue;
        }
    }
    catch( e )
    {
        console.log('updateStorageValue :: exception ... ',e);
    }
}
//Chnaged by Prasad on 01/06/2020 [to set storage value] END

//Added by Prajyot R. on 01-JUN-2020 [For Apply Aggregation] Start
export function APPLY_AGGREGATION(data: any, groupByColumns: any, aggregateObj: any)
{
    console.log('APPLY_AGGREGATION groupByColumns : ', groupByColumns, 'aggregateObj : ', aggregateObj);
    var _data = DEEP_CLONE(data);
    var groupedArr = GROUP_BY_KEYS(_data, groupByColumns);
    console.log('APPLY_AGGREGATION groupedArr', groupedArr);
    /*
    aggregateObj = {
        'SUM' : '',
        'AVG' : '',
        'MIN' : '',
        'MAX' : '',
        'COUNT' : '',
    };
    */
    if( aggregateObj.SUM )
    {
        groupedArr = SUM(groupedArr, aggregateObj.SUM, true);
        console.log('APPLY_AGGREGATION SUM', groupedArr);
    }
    if( aggregateObj.AVG )
    {
        groupedArr = AVERAGE(groupedArr, aggregateObj.AVG, true)
        console.log('APPLY_AGGREGATION AVERAGE', groupedArr);
    }
    if( aggregateObj.MIN )
    {
        groupedArr = MINMAX(groupedArr, aggregateObj.MIN, 'MIN');
        console.log('APPLY_AGGREGATION MIN', groupedArr);
    }
    if( aggregateObj.MAX )
    {
        groupedArr = MINMAX(groupedArr, aggregateObj.MAX, 'MAX');
        console.log('APPLY_AGGREGATION MAX', groupedArr);
    }
    if( aggregateObj.COUNT )
    {
        groupedArr = COUNT(groupedArr, aggregateObj.COUNT);
        console.log('APPLY_AGGREGATION sumArr', groupedArr);
    }

    if(groupedArr)
    {
        var aggregateArr: any = [];
        groupedArr.map((objArr: any)=>{
            if ( objArr instanceof Array ) {
                aggregateArr.push( objArr[0] );
            }
        });
        if( aggregateArr.length > 0 )
        {
            return aggregateArr;
        }
    }
    return data;
}


export function MINMAX( array: any, keystring: any, opt: any ) : any 
{
    var keyList = keystring.split(',');
    keyList = keyList.map((key: any) => { return key.trim() });
    if( keystring.lastIndexOf(',') == keystring.length - 1 )
    {
        keyList.pop();
    }
    console.log('minmax function : ', opt, array);
    console.log('keyList : ',keyList);

    var returnArray = array.map(( objArr: any ) => {
        //console.log( objArr, objArr instanceof Array );
        if ( objArr instanceof Array )
        {
            //isArray = true;
            for(var key of keyList)
            {
                var _value = 0;
                objArr.map( function( cur ) {
                    //console.log( opt, key, _value , cur[key] );
                    if( opt == 'MAX' && ( _value < cur[key] ) )
                    {
                        _value = cur[key];
                    }
                    else if( opt == 'MIN' && ( _value > cur[key] ) )
                    {
                        _value = cur[key];
                    }
                });
                objArr[0][key] = _value;
            }
        }
        return objArr;
    } );

    console.log('returnArray : ',returnArray);
    return returnArray;
}


export function COUNT( array: any, keystring: any ) : any 
{
    var keyList = keystring.split(',');
    keyList = keyList.map((key: any) => { return key.trim() });
    if( keystring.lastIndexOf(',') == keystring.length - 1 )
    {
        keyList.pop();
    }
    console.log('count function : ', array);
    console.log('keyList : ',keyList);

    var returnArray = array.map(( objArr: any ) => {
        //console.log( objArr, objArr instanceof Array );
        if ( objArr instanceof Array )
        {
            //isArray = true;
            for(var key of keyList)
            {
                objArr[0][key] = objArr.length;
            }
        }
        return objArr;
    } );

    console.log('returnArray : ',returnArray);
    return returnArray;
}

//Added by Prajyot R. on 01-JUN-2020 [For Apply Aggregation] Ends
