

var App = angular.module('myApp',  ['firebase','ngSanitize']);

App.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                     scope.$eval(attrs.ngEnter);
                });
 
                event.preventDefault();
            }
        });
    };
});

App.controller("mainCtrl", function($scope,$timeout,$firebaseObject,$rootScope,$http,$sce) 
{

$scope.variables = {};	
$scope.recentUsers = [];
$scope.messages = [];
$scope.session;

	$.get( base_url+'Home/get_session', function( data ) 
	{
	    $scope.session = jQuery.parseJSON(data);
	    //console.log($scope.session)
	})

	$timeout(function()
	{
		$.get( base_url+'Home/get_opponentData', function( data ) 
		{
			//console.log("connect")
		    var opponent_user = jQuery.parseJSON(data);
		    if(opponent_user.status!='error')
		    {$scope.load_chat(opponent_user);}
		})
	},200);
	

	$scope.load_recent_chat = function() 
	{
		$.ajax({
		url: base_url+"Home/get_recent_chat",
		type: "GET",
		dataType: "json",
								
			success: function(result,status){
			$timeout( function(){	
			 $scope.recentUsers = result;
			  //console.log($scope.recentUsers); 
			  //console.log($scope.allUsers);
			  
			},100);
			  				  
			},
			complete(xhr,status){
				/*console.log('completed')*/
			},
			error(xhr,status,error){
			   // alert(status)
			}
		})
		$timeout(function() {$scope.load_recent_chat();}, 3000);
	}

	$scope.load_recent_chat();


	$.ajax({
	url: base_url+"Home/get_all_chat_users",
	type: "GET",
	dataType: "json",
							
		success: function(result,status){
		$timeout( function(){	
		 $scope.allUsers = result;
		  //console.log($scope.allUsers,$scope.recentUsers); 
		},100);
		  				  
		},
		complete(xhr,status){
			/*console.log('completed')*/
		},
		error(xhr,status,error){
		   // alert(status)
		}
	})
		
	

$scope.load_chat =function(object)
{
	
	if(angular.isDefined(object.chat_id))
	{
		$scope.chat_id = object.chat_id;
	}

	$scope.list = [];
	if($scope.session.type=="DOCTOR" || $scope.session.type=="COLLABORATOR")
	{
		$scope.opponent = {'name' : object.pat_name,'id' : object.patient_id,'pic' : object.pat_pic};
		$scope.chat_id = 'P'+object.patient_id+'@_@D'+$scope.session.id;
	}
	else
	{
		$scope.opponent = {'name' : object.doc_name,'id' : object.doctor_id,'pic' : object.doc_pic};
		$scope.chat_id = 'P'+$scope.session.id+'@_@D'+object.doctor_id;
	}
	//console.log($scope.chat_id)
	//console.log($scope.opponent)
	$('.full_screen_loader').removeClass('hidden');
	var connRef = firebase.database().ref('chats/'+$scope.chat_id+'/').orderByChild("time");
	connRef.on('value', function(snapshot) 
	{
		$('.full_screen_loader').addClass('hidden');
		$scope.messages = snapshot.val();
		angular.forEach($scope.messages,(data,key)=>{
			var d = new Date(data.time);
			var dat=(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
			var a = $scope.list.indexOf(dat);
			if(a=="-1")
			{ 
			  $scope.list.push(dat);
			  data.show_date = true;
			}
			else
			{data.show_date = false;}
			
		})
		$timeout(function(){$scope.$apply()},5);
		$timeout(function() 
		{
			var scroller = document.getElementById("chat_autoscroll");
			scroller.scrollTop = scroller.scrollHeight;
		}, 10,false);
		//console.log($scope.messages)
	});
// connectedRef.on("value", function(snap) {
}




$scope.test = function()
{
	alert("!");
}


  $scope.trustAsHtml = function(string) 
  {
    return $sce.trustAsHtml(string);
	};

$scope.sentmsg = function (msg,opp)
{
	if(msg.length>0)
	{
		
		//console.log(msg,$scope.session,$scope.opponent)
		if($scope.session.type=="DOCTOR" || $scope.session.type=="COLLABORATOR")
		{
			var object = {	'doctor_id':Number($scope.session.id),
					'doctor_name':$scope.session.name,
					'doctor_photo':$scope.session.profile_photo,
					'message':msg,
					'sender_type' : 1,
					'patient_id':Number($scope.opponent.id),
					'patient_name':$scope.opponent.name,
					'patient_photo':$scope.opponent.pic,
					'photo_url':"",
					'time':new Date().getTime(),
					'type':0,
					'video_url':""};

			//UPDATING RECENT MSG IN MYSQL DB
	   		var recent_obj = { 'chat_id': $scope.chat_id,
						  'patient_id': Number($scope.opponent.id),
						  'doctor_id': Number($scope.session.id),
						  'sender_type':1,
						   'msg': msg,
						   'photo_url': '', 
						   'video_url': '',
							'type': 0, 
						   'time': new Date().getTime()
						}
		}

		if($scope.session.type=="PATIENT")
		{
			var object = {	'doctor_id':Number($scope.opponent.id),
					'doctor_name':$scope.opponent.name,
					'doctor_photo':$scope.opponent.pic,
					'message':msg,
					'sender_type' : 0,
					'patient_id':Number($scope.session.id),
					'patient_name':$scope.session.name,
					'patient_photo':$scope.session.profile_photo,
					'photo_url':"",
					'time':new Date().getTime(),
					'type':0,
					'video_url':""};

			//UPDATING RECENT MSG IN MYSQL DB
	   		var recent_obj = { 'chat_id': $scope.chat_id,
						  'patient_id': Number($scope.session.id),
						  'doctor_id': Number($scope.opponent.id),
						  'sender_type':0,
						   'msg': msg,
						   'photo_url': '', 
						   'video_url': '',
							'type': 0, 
						   'time': new Date().getTime()
						}
		}
		
	  //firebase.database().ref('chats/'+$scope.chat_id+'/').push(object); //Update msg in firebase
	  var newRef = firebase.database().ref('chats/'+$scope.chat_id+'/').push().then((snap) => 
	  {
	  	object.id = snap.key;
	  	firebase.database().ref('chats/'+$scope.chat_id+'/'+snap.key).set(object); //Update msg in firebase
     	//console.log(snap.key );
  	  });
		
		if($scope.session.type=="DOCTOR" || $scope.session.type=="COLLABORATOR")
		{recent_obj.sender_type = 1;}
		if($scope.session.type=="PATIENT")
		{recent_obj.sender_type = 0;}

	   $.post(base_url+"Home/update_recent_chat",recent_obj,(data,status)=>{
	   	//console.log(data)
	   	$timeout( function()
	   	{	
			 $scope.recentUsers = JSON.parse(data);
			},100);
	   });

	   $scope.variables.texttosent = '';
	}
	

}

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}


})