import { Component, OnInit , ViewEncapsulation , AfterViewChecked ,ChangeDetectorRef ,Input, Output, EventEmitter} from '@angular/core';
import { DomSanitizer , SafeHtml } from '@angular/platform-browser';
import { UserTaskService } from '../user-task/user-task.service';

import { DatePipe } from '@angular/common'
import { SORT,GROUP_BY, DUAL_GROUP_BY, GROUP_BY_KEYS, SUM } from '../../plugin/utils/dashboard-plugin-util';

@Component({
  selector: 'feed-component',
  templateUrl: './feed-component.component.html',
  styleUrls: ['./feed-component.component.css'],
  encapsulation: ViewEncapsulation.None, 
  providers:[DatePipe]

})
export class FeedComponentComponent implements OnInit , AfterViewChecked  {

    @Input('data') reportData : any;
    @Output() onDrillDown: EventEmitter<any> = new EventEmitter();
    @Output() onPerformAction: EventEmitter<any> = new EventEmitter();
    link_metadata:any;
    feedData: any[] =[];
    feedChildData: any[]=[];
    custName:any;
    custCode:any;
    safeHtmlvalue!:SafeHtml;
    shHtml:any;      
    feedsConfig:any;
    layoutProtoType:any;

    // Added by Samruddhi for quick access panel
    context: any = {};
    
    //to do common service for feed component
  constructor(public datepipe: DatePipe,private cdr: ChangeDetectorRef, public userTaskService : UserTaskService ) { }

  ngOnInit()
  {
       console.log("reportData in feed-component ==  > ", this.reportData);

       this.feedsConfig = this.reportData.feedsConfig;
       this.layoutProtoType = this.reportData.layoutProtoType;
       //Changed by Sadique 16/12/2020 [to resolve landing dashboard related issue] START
       try
       {
           this.processData(this.reportData);
       }
       catch(e)
       {
           console.log( "Exception processData :", e );
       }
       //Changed by Sadique 16/12/2020 [to resolve landing dashboard related issue] END
       /*
       //this.feedData = this.reportData.data;
       var result = JSON.parse(this.reportData.data);
       this.feedData= GROUP_BY(result,'SALE_ORDER');
       for(var data of this.feedData)
       {
           for(var objectData of data.objects){
               if(objectData.ORDER_DATE){
                   this.custCode=objectData.CUST_CODE;
                   this.custName=objectData.CUST_NAME;
                   console.log('custCode custName:::::::::',this.custCode,this.custName);
                   var orderDate=objectData.ORDER_DATE;
                   orderDate=this.datepipe.transform(orderDate,  'dd/MM/yy');
                   objectData.ORDER_DATE=orderDate;
               }
           }
       }
       */
       this.shHtml = this.reportData.compHTML;
       console.log('Print shHtml::::',this.shHtml);
       this.context = this.feedData;
       console.log('Print context 75:::::',this.context);
       this.link_metadata = this.reportData.link_metadata;
       console.log("FeedComponentComponent start",new Date(), this.layoutProtoType); 
   }
    
    ngAfterViewChecked(){
        //your code to update the model
        this.cdr.detectChanges();
    }
    
    processData(data:any)
    {
        console.log('processData :: feedData :: ', this.feedData);
        console.log('processData :: data :: ', data);
        //Changed by Sadique 16/12/2020 [to resolve landing dashboard related issue] START
        try
        {
            for( var feedData of data.data ) {
                console.log('feedData :: ', feedData);
                console.log(feedData.IMAGE);
                console.log(feedData.ICON);
                console.log('Doctot Name : ',feedData.DR_NAME);
                //console.log(feedData.IMAGE.length);
                var imageIntitials = 'NA';
                var titleIcon = feedData.DR_NAME;
                var initials = titleIcon.match(/\b\w/g) || [];
                imageIntitials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
                /*if( !feedData.ICON || feedData.ICON == "" ) {
                    var titleIcon = feedData.ICON;
                    if( titleIcon ) {
                        var initials = titleIcon.match(/\b\w/g) || [];
                        imageIntitials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
                    }    
                }*/
                console.log('imageIntitials :: ', imageIntitials);
                feedData.IMAGE = imageIntitials;
                console.log('feedData.IMAGE #2 :: ', feedData.IMAGE);
               // feedData.IMAGE
            }
        }
        catch(e)
        {
            console.log( "Exception feedData :", e );
        }
        //Changed by Sadique 16/12/2020 [to resolve landing dashboard related issue] END
        var feedDataLocal = [];
        console.log('Feed data  getColumnData',data);
        try
        {
            feedDataLocal = JSON.parse(this.reportData.data);
        }
        catch(e)
        {
            feedDataLocal = this.reportData.data;
        }
        
        this.feedData = Object.assign([], feedDataLocal);
        if(this.feedsConfig)
        {
              this.feedData = DUAL_GROUP_BY(this.feedData,this.feedsConfig);
              console.log('After DUAL_GROUP_BY this.feedData',this.feedData);
            for(var data of this.feedData)
              {
                  if( data.objects )
                  {
                      for(var objectData of data.objects){
                          if(objectData.ORDER_DATE){
                              var orderDate=objectData.ORDER_DATE;
                              orderDate= this.formatDate(orderDate);
                              // orderDate=this.datepipe.transform(orderDate,  this.dateFormat);
                              objectData.ORDER_DATE=orderDate;
                              //  console.log('order date>>>',objectData.ORDER_DATE);
                          }
                      }
                  }
              }                              
             console.log('after dual group by',this.feedData);
        }

        var columnGroup=this.reportData.column_group;
        if(columnGroup[0] !=null)
        {
            for(var colGroup of columnGroup)
            {
               var columns=colGroup.columns;
               console.log('columns>>>>',columns)

               if( columns != null )
               {
                   if( columns instanceof Array )
                   {
                       for(var colms of columns)
                       {
                           console.log('columns::::',colms)
                          // column=colms.column;
                           var aggFunction=colms.aggFunction;
                           var value=colms.value;
                           var typeOfColumn=colms.type;
                           var order=colms.order;
                           if(aggFunction=='SORT_BY')
                           {
                               var notNullList = this.feedData.filter( x => {return x[value]});
                            
                               var nullList = this.feedData.filter( x => {return !x[value]});
                              
                               console.log('Null array',notNullList);
                               var sortedArray = SORT(notNullList,value ,typeOfColumn,order);
                               this.feedData = sortedArray.concat(nullList); 
                               console.log('after sort by',this.feedData);
                           }
                           else if(aggFunction=='GROUP_BY')
                           {
                                 this.feedData = GROUP_BY(this.feedData,value);
                                for(var data of this.feedData)
                                 {
                                      for(var objectData of data.objects){
                                          if(objectData.ORDER_DATE){
                                              var orderDate=objectData.ORDER_DATE;
                                              orderDate= this.formatDate(orderDate);
                                             // orderDate=this.datepipe.transform(orderDate,  this.dateFormat);
                                              objectData.ORDER_DATE=orderDate;
                                            //  console.log('order date>>>',objectData.ORDER_DATE);
 
                                           }
                                       }
                                 }                              
                                     console.log('after group by',this.feedData);
                           }
							//Added by Yogesh Mohite [ group by and sum ] 24/07/2019
                           else if(aggFunction=='GROUP_BY_KEYS')
                           {
                               this.feedData = GROUP_BY_KEYS(this.feedData, value);
                               console.log('After GROUP_BY_KEYS :: ' , value, this.feedData);
                           }
                           else if(aggFunction=='SUM')
                           {
                               this.feedData = SUM(this.feedData, value);
                               console.log('After SUM :: ' , value, this.feedData);
                           }
                       }                  
                   }
                   else
                   {
                       var aggFunction=columns.aggFunction;
                       var value=columns.value;
                       var typeOfColumn=columns.type;
                       if(aggFunction=='SORT_BY')
                       {
                           
                           console.log('aggFunction:::',aggFunction,value,typeOfColumn,this.feedData);
                           var notNullList = this.feedData.filter( x => {return x[value]});
                        
                           var nullList = this.feedData.filter( x => {return !x[value]});
                          
                           console.log('notNullList>>',notNullList);
                           console.log('nullList>>>',nullList);
                           var sortedArray = SORT(notNullList,value ,typeOfColumn,order);
                           this.feedData = sortedArray.concat(nullList); 
                     //    this.feedData = SORT(this.feedData,value,typeOfColumn);
                             console.log('after sort by',this.feedData);
                       }
                       else if(aggFunction=='GROUP_BY')
                       {
                             this.feedData = GROUP_BY(this.feedData,value);
                             for(var data of this.feedData)
                             {
                                  for(var objectData of data.objects){
                                      if(objectData.ORDER_DATE){
                                          var orderDate=objectData.ORDER_DATE;
                                          orderDate= this.formatDate(orderDate);
                                        //  orderDate=this.datepipe.transform(orderDate,  this.dateFormat);
                                          objectData.ORDER_DATE=orderDate;
                                    //      console.log('order date::',objectData.ORDER_DATE);
                                       }
                                   }
                             } 
                             console.log('after group by',this.feedData);
                       }
						// Added by Yogesh [group and sum ] 24/07/2019
                       else if(aggFunction=='GROUP_BY_KEYS')
                       {
                           this.feedData = GROUP_BY_KEYS(this.feedData, value);
                           console.log('After GROUP_BY_KEYS :: ' , value, this.feedData);
                       }
                       else if(aggFunction=='SUM')
                       {
                           this.feedData = SUM(this.feedData, value);
                           console.log('After SUM :: ' , value, this.feedData);
                       }
                   }    

               }
            }
         }
     }

    formatDate(date:any)
    {
      console.log('Date in  formatDate>>>>',date);    
      if(date.indexOf('/') > -1)
      {
          var splitDate =date.split("/");
          let firstdate= splitDate[0];
          let month= splitDate[1];
          var dateStr=month+'/'+firstdate+'/'+splitDate[2];
          console.log('updated formatDate::: :',dateStr);
      }
      else
      {
          var splitDate =date.split("-");
          let firstdate= splitDate[0];
          let month= splitDate[1];
          var dateStr=month+'-'+firstdate+'-'+splitDate[2];
          console.log('updated formatDate>>>>',dateStr);
      }
         return dateStr; 
    }

    _onDrillDown(rowData:any)
    {
        var drillColumnName = rowData.drillFrom;
        var drillColumnValue = rowData[drillColumnName];
        var selectedFieldInfo = {
            "column" :  drillColumnName,
            "value" : drillColumnValue,
            "linkMetadata" : this.link_metadata,
            "rowData" : rowData
        };
        this.onDrillDown.emit(selectedFieldInfo);
    }
    
    getInitials(fulltext:any)
    {
        var initialtext = 'NA';
        if( fulltext )
        {
            var initials = fulltext.match(/\b\w/g) || [];
            initialtext = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
        }
        return initialtext;
    }
    
    evaluate(status:any)
    {
        var backgroundColor = '';
        switch(status)
        {
            case 'P' : backgroundColor = 'rgb(255, 196, 35)'; break;/* Added By Pravin K on 30-JAN-20 [rgb(255, 211, 90)] */
            case 'C' : backgroundColor = 'rgb(0, 199, 153)'; break;
            default : backgroundColor = 'rgb(252, 101, 101)'; break;
        }
        return { 'background': backgroundColor };
    }
    
    changeCurrentStatus(event:any, feedData:any)
	{
		// Added By Pravin K on 12-JAN-20 [START]
		console.log('changeCurrentStatus ::event ',event);
		console.log('changeCurrentStatus:: feedData :', feedData);

		if(event.target.checked)
		{
			var isConform = confirm("Are you sure this task has been completed ?");
	  		if( isConform )
	  		{
				var tranId = feedData.TRAN_ID;
				var currStatus = 'C';
				console.log('changeCurrentStatus ::tranId['+tranId+'], currStatus['+currStatus+']',event);
				this.userTaskService.updateUserTaskStatus( tranId, currStatus ).subscribe(
	          		result => {
	            		console.log("Response from userTaskService.updateUserTaskStatusresult::result",result);
	            		feedData.CURR_STATUS = currStatus;
	            
	            		feedData['isDataRefresh'] = true;
						this.onDrillDown.emit(feedData);
	          		});
	  		}
	  		else
	  		{
	  			event.target.checked = false;
	  			feedData['UPD_STATUS'] = false;
	  		}
	  		console.log('changeCurrentStatus ::isConform[',isConform,'], event.target.checked[',event.target.checked,']');
	  		console.log('changeCurrentStatus:: feedData :', feedData);
		}
		// Added By Pravin K on 12-JAN-20 [END]

	}

	openUserTask( selectedFeedData:any )
	{
		console.log("open userTask");
		
		var link = {
			AutoInvoke: "",
			DisplayMode: "1",
			FormNo: "1",
			LineNo: "1",
			LinkForm: "LINK",
			LinkType: "A",
			RecordSpecific: "1",
			TargetObject: "user-task",
			linkId: "",
			feedData: selectedFeedData
		};
		this.onPerformAction.emit(link);
		
		//onPerformAction
	
	}

    // Added by Samruddhi for quick access panel
    evalFunction(evalString:any) 
    {
        // console.log("evalString:::::", evalString);
        return eval(evalString);
    }

   /* _onDrillDown(data:any, drillFrom:any) {
        console.log( '_onDrillDown : [', data , '] ')
        data['drillFrom'] = drillFrom;
        this.onDrillDown.emit(data);
    }*/
}
