import { Component, OnInit, Input, NgZone,EventEmitter } from '@angular/core';
import { UserTaskService } from './user-task.service';
import { DashboardDatamodelService } from '../dashboard/dashboard-datamodel.service';

@Component({
  selector: 'user-task',
  templateUrl: './user-task.component.html',
  styleUrls: ['./user-task.component.css'],
  providers: [UserTaskService],
})
export class UserTaskComponent implements OnInit {
  
  @Input() pluginMetadata:any;
  hostUrl:any;
  dashboardName='USER_TEAM_DM'
  isNullData:any;
  refreshDate:any;
  userList:any ={};
  userIdAssign='9821';
  taskData:any = {};
  isFirstChange:any = true;
  lastSelection:any;
 
  
  displayMetadata =  {
    "suggestMetadata" : "<EMP_NAME>",
    "valueFields":"EMP_NAME",
    "chipMetadata":"<EMP_NAME>"
  }
  
  @Input() data = {
    title: "Adding Task",// Added by Pravin K on 23-MAY-20
    mode: "add",
    fields: [
      // Added by Pravin K on 23-MAY-20 [Currently not required] START
      // {   
      //   label: "Activity Type",
      //   type: "dd",
      //   options: [
      //     "Support",
      //     "Fields Work"
      //   ],
      //   id:'taskType'
      // },  // Added by Pravin K on 23-MAY-20 [Currently not required]   END
      {
        label: "Task Details : ", // Added by Pravin K on 23-MAY-20
        type: "tf",
        id:'taskDescr',
        value: ''
      },
      {
        label: "Assign To : ",
        type: "tf",
        autosuggest:{
        chipEnable:false,
        dataSource:this.userList,
        selectedUser:""
        },
        id:'userIdAssign'
      }
    ]
  };

//private userTaskService: UserTaskService,
  constructor( private userTaskService: UserTaskService,
  private dashboardDatamodelService: DashboardDatamodelService, public zone: NgZone) { }
  
  ngOnInit() {
  
    console.log('UserTaskComponent ---- pluginMetadata', this.pluginMetadata);
    
    if(this.pluginMetadata.compData && this.pluginMetadata.compData.feedData)
    {
    	var feedData = this.pluginMetadata.compData.feedData;
    	console.log("feedData:",feedData);
    	
    	var dataArr = this.data.fields
    	console.log("dataArr:",dataArr);
		
		for (let i = 0; i < dataArr.length; i++) 
		{
		 	var obj:any =  dataArr[i];
		 	if(obj.id=='taskDescr')
		 	{
		 		obj.value = feedData.TASK_DESCR;
		 		this.taskData.taskDescr = feedData.TASK_DESCR;
		 	}
		 	else if(obj.id=='userIdAssign')
		 	{
		 		obj.autosuggest.selectedUser = feedData.ASSIGNEE_NAME;
			    this.taskData.userIdAssign = feedData.USER_ID__ASSIGNED;
			    //Added by Pravin K on 17-MAR-20[for processes after done] START
    		 	if(feedData.EMP_NAME)
                {
                    obj.autosuggest.selectedUser = feedData.EMP_NAME;
                    this.taskData.userIdAssign = feedData.EMP_CODE;
                }
				//Added by Pravin K on 17-MAR-20[for processes after done] END
		 	}
		}
		this.taskData.tranId = feedData.TRAN_ID;
		
		console.log("this.data:",this.data);
		
		
    	
    }
    this.hostUrl = this.userTaskService.getHostURL();
    console.log('hostUrl : ',this.hostUrl);
   
    // this.datamodelService.getDataModelData(this.dataSource,"", "", false).subscribe(
    this.dashboardDatamodelService.getDataModelData(this.dashboardName,'', false,true, false, false).subscribe(
      (dashboardData:any) => {
        console.log('result of servlet::',dashboardData);
        if(dashboardData){

          this.refreshDate = new Date();
          console.log("11 ::dashboardData:  ",dashboardData);
          if(dashboardData.length == 0 || dashboardData.status == 'Failure' || (dashboardData.result && dashboardData.result.status == 'Failure') || (dashboardData.data && dashboardData.data.length == 0)){
              this.isNullData = true;
          }
          else{
            this.isNullData = false;
            if(dashboardData){
              
              if(dashboardData.reponse != "loading"){
                
                console.log("dashboardDatamodelService::dashboardData:  ",dashboardData);
                
                var obj_deta =[{"THUMB_OBJ":"strg_code",
                  "THUMB_ALT_COL":"strg_name",
                  "LAYOUT":"{\"simple\":\"\",\"template\":\"<div>{{strg_name}} - {{sh_descr}}<\/div>\"}",
                  "THUMB_IMAGE_COL":"strg_code"
                  },
                  {"DATAMODEL_NAME":"CUSTOMERCODES",
                  "FILTER_EXPR":"locality_code == :locality_code: && visited_with_team == :visited_with_team:",
                  "FIELD_NAME":"STRG_CODE"
                  }];
                console.log(" obj_deta:  ",obj_deta);
                var allDataArr = obj_deta.concat(dashboardData);
                console.log(" allDataArr:  ",allDataArr);

                var dataObj = {"DETAILS":allDataArr,"details":allDataArr};
                console.log(" dataObj:  ",dataObj);
              
                this.userList = dataObj;
                console.log("::userList:  ",this.userList);

                  /*  this.zone.run(() => {
                        console.log( 'view refreshed' );
                    }); */
              }
            }
          }
        }
        console.log('END TIME 2',new Date());
      });
    }

    onTfChange(event:any, iconTarget: HTMLDivElement, id:any) {
      var val = event.target.value;
      console.log("onTfChange value",val);
      console.log("val ",val);
      if(val)
      {
        this.taskData[id] = val
        console.log("onTfChange taskData",this.taskData);
      }
    }
  
    onddChange(event:any, value:any, id:any)
    {
      console.log("onddChange event.value",event.value);
      if(event.value)
      {
        this.taskData[id] = event.value
        console.log("onddChange taskData",this.taskData);
      }
    }

    changeSelection(value:any, id:any)
    {
      console.log("changeSelection.. " , value);
      var change = false;
      
      console.log("cthis.lastSelection" , this.lastSelection);
      if(this.lastSelection)
      {
	      var currTime = new Date().getTime();
	      console.log("cthis.currTime" , currTime);
	      
	      var diff = (currTime-this.lastSelection)/1000
	      
	      console.log("diff : " , diff);
	      
	      if(diff > 2)
	      {
	      	change = true;
	      }
      	
      }
      else
      {
      	change = true;
      }
      
      if(change)
      {
	      if(value.detail.EMP_CODE)
	      {
	        this.taskData[id] = value.detail.EMP_CODE
	        console.log("changeSelection taskData",this.taskData);
	      }
      }
     
      
      this.lastSelection = new Date().getTime();
    }
    
    saveTask(){
      console.log("saveTask taskData",this.taskData);

      var taskDescr =  this.taskData.taskDescr || '';
      var userIdAssign =  this.taskData.userIdAssign || '';
      var taskType = this.taskData.taskType || '';
      var tranId = this.taskData.tranId || '' ;

      var userTaskData={"CURR_STATUS":"P",
      "USER_ID__ASSIGNED":userIdAssign, 
      "TASK_DESCR":taskDescr,
      "TASK_TYPE":taskType,
      "TRAN_ID":tranId,
      };
      console.log("..save::userTaskData ", userTaskData);

      if(userIdAssign && taskDescr)
      {
      
      /*	var dataArr = this.data.fields
    	console.log("dataArr:",dataArr);
		
		for (let i = 0; i < dataArr.length; i++) 
		{
		 	var obj =  dataArr[i];
		 	if(obj.id=='taskDescr')
		 	{
		 		obj.value = '';
		 	}
		 	else if(obj.id=='userIdAssign')
		 	{
		 		obj.autosuggest.selectedUser = '';
			    this.taskData.userIdAssign = '';
		 	}
		}
 		this.taskData = {};
 		this.zone.run(() => {
                        console.log( 'view refreshed' );
                    });
 		
	    console.log("this.taskData:",this.taskData);
	    console.log("this.data",this.data);*/
		    	
        this.userTaskService.saveUserTask( userTaskData ).subscribe(
          (result:any) => {
            console.log("Result from userTaskService.saveUserTask::result:",result);
            
            if(result.status==200)
            {
            	var dataArr = this.data.fields
		    	console.log("dataArr:",dataArr);
				
				for (let i = 0; i < dataArr.length; i++) 
				{
				 	var obj:any =  dataArr[i];
				 	if(obj.id=='taskDescr')
				 	{
				 		obj.value = '';
				 	}
				 	else if(obj.id=='userIdAssign')
				 	{
				 		obj.autosuggest.selectedUser = '';
                        this.taskData.userIdAssign = '';
                        this.taskData.taskDescr = '';
				 	} 
				} 
		 		this.taskData = {}; 
		 		
		 		//Added by Pravin K on 17-MAR-20[for processes after done] START
		 		this.setDefaultValues();
		    	
		 		console.log("this.taskData:",this.taskData);
		    	alert("Task saved successfully.");
		 		//Added by Pravin K on 17-MAR-20[for processes after done] END
		    	
            }
          });
      }
      else
      {
        alert("Please check the description and the assigned user these should not  be empty.")
      }
    }
    autosuggestChange(){ }
    
    //Added by Pravin K on 17-MAR-20[for processes after done] START
     
    setDefaultValues()
    {
        
        console.log("setDefaultValues:");
        var dataArr = this.data.fields
        
        for (let i = 0; i < dataArr.length; i++) 
        {
            var obj:any =  dataArr[i];
            if(obj.id=='taskDescr')
            {
                obj.value = "";
            }
            else if(obj.id=='userIdAssign')
            {
                obj.autosuggest.selectedUser = "";
            }
        }
        var taskDescrElm:any = document.getElementById("taskDescr");
        if(taskDescrElm)
        {
            taskDescrElm["value"]=""; 
        }
        this.taskData.userIdAssign = '';
        this.taskData.taskDescr = '';
        
        this.zone.run(() => {
            console.log( 'view refreshed' );
        });
        
        console.log("setDefaultValues::this.data:",this.data);
    }
  //Added by Pravin K on 17-MAR-20[for processes after done] END
  }
