/*
 * virtualMeetingBlog.js
 * Ajax / JQuery support for virtual meetings blog feature
 */
function showBlogSuccessMessage(msg,message)	{
	let blogMessageArea = $("#blogMessageArea");
	blogMessageArea.empty();
	if(msg.message !== undefined && msg.message.length >0){
		blogMessageArea.append('<span class="info">' + msg.message + '</span>');
	}else{
		blogMessageArea.append('<span class="info">' + message + '</span>');
	}
}
function showBlogErrorMessage(message)	{
	let blogMessageArea = $("#blogMessageArea");
	blogMessageArea.empty();
	blogMessageArea.append('<span class="error">' + message + '</span>');
}
function deleteBlogPost(postId)		{
	if (!confirm ("Please confirm you want to delete this comment:\n\nClick OK to proceed, or Cancel"))	{
		console.log("user cancelled deletion");
		return false;
	}
	// disable button, show progress indicator
	$('#blogSave').prop('disabled', true);
	$('#spinner').show();
	
	$("#blogAction").val("delete");
	$("#blogPostId").val(postId);
	var csrfdata=document.getElementById("csrfparameterName").value;
	csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
	$.ajax({
		type: "POST",
		method: "POST",
		data: $("#blogForm").serialize(),
		url:  "virtualMeetingHandler.form?" + csrfdata,
		success: function(msg){   
			console.log ('ajax success: items returned: ' + msg.blogListingSize);
			$("#blogComment").val('');
			$("#blogPostId").val('');
			showBlogSuccessMessage(msg,"The comment has been deleted.");
			renderBlogPosts(msg);
			console.log('end of ajax success');
			var saveButton = document.getElementById('saveDataButton');
			if(saveButton==null || (saveButton && saveButton.style.border != '1px dashed red'))
				unsavedData=false;
			blogUnsavedFlag = false;
		},
		error: function(msg){
			console.log('ajax error: msg');
			showBlogErrorMessage("Error: it was not possible to remove the comment.");
			
		}
	});

	// enable button, hide progress indicator
	$('#blogSave').prop('disabled', false);
	$('#spinner').hide();


	
}
$("#blogForm").on("submit", function (e) {
	console.log('on submit form - start');
    e.preventDefault();
    console.log("Blog action is:" + $("#blogAction").val());
    if ($("#blogAction").val() === "comment")
	    checkAndAddBlogPost();
	console.log('on submit form - finished');
	return false;
});
/*
function submitForm()	{
	console.log('submit form - start');
	$("#blogForm").submit();
	console.log('submit form - finished');
}
*/
$("#blogSave").click ( function () {
	$("#blogAction").val("comment");
});

var blogUnsavedFlag = false;	// check if user has an unsaved blog post

$('#blogComment').on("change", function (e)	{
	blogUnsavedFlag = true;
});

$('#blogComment').on("focus", function (e)	{
	if (checkLock())	{
		setBlogLockedUI(true);
		return;
	}
});

function checkAndAddBlogPost ()		{
	if (checkLock())	{
		setBlogLockedUI(true);
		return;
	}
	let blogComment = $("#blogComment");
	console.log("comment is '" + blogComment.val() + "', length=" + blogComment.val().length);
	if ( blogComment.val().length === 0 )	{
		alert("Please enter a comment first");
		blogComment.focus();
		return false;
	}
	if (!confirm ("Your comment will be added to the Virtual MDT discussion:\n\nClick OK to proceed, or Cancel to resume editing"))	{
		console.log("user cancelled");
		return false;
	}
	console.log ("Add the blog post, refresh the page");
	// disable button, show progress indicator
	$('#blogSave').prop('disabled', true);
	$('#spinner').show();
	
	$("#blogAction").val("comment");
	var csrfdata=document.getElementById("csrfparameterName").value;
	csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
	$.ajax({
		type: "POST",
		method: "POST",
		data: $("#blogForm").serialize(),
		url:  "virtualMeetingHandler.form?" + csrfdata,
		beforeSend:  function(){
			console.log("before send comment is " + $("#blogComment").val());
		},
		success: function(msg){   
			console.log ('ajax success: items returned: ' + msg.blogListingSize);
			$("#blogComment").val('');
			showBlogSuccessMessage(msg,"Your comment has been added.");
			renderBlogPosts(msg);
			console.log('end of ajax success');
			var saveButton = document.getElementById('saveDataButton');
			if(saveButton==null || (saveButton && saveButton.style.border != '1px dashed red'))
				unsavedData=false;
			blogUnsavedFlag = false;
		},
		error: function( jqXHR, textStatus, errorThrown){
			console.log('ajax error: msg ' + JSON.stringify(jqXHR));
			console.log('textstatus ' + textStatus);
			showBlogErrorMessage("Error: it was not possible to add your comment.");			
		},
		statusCode: {
			403: function() {
				showBlogErrorMessage("Your session has ended.  Please log in.");
			}
		}

	});

	// enable button, hide progress indicator
	$('#blogSave').prop('disabled', false);
	$('#spinner').hide();

}
// render blog posts via JS in response to new ajax posts
function renderBlogPosts (msg)	{
	var blogListingSize = msg.blogListingSize;
	console.log ('starting rendering items= ' + blogListingSize);
 	$("#blogPosts").empty();
	for(var index=0; index<msg.blogListingSize; index++){
		var blog = msg.blogListing[index];
	 	var row = '<div class="blogRow">' + 
	 				'<div class="blogUser">' + blog.userMakingComment.fullName + '<br/>' +
	 				'<div class="blogHospital">' + blog.userMakingComment.hospital.hospitalName + '</div></div>' +
	 				'<pre class="blogComment">' + blog.comment + '</pre>' +
	 				'<div class="blogDate">' + blog.formattedDate + 
					'<div class="blogDelete"><a href="javascript:deleteBlogPost(' + blog.id + ')" class="blogDeleteStyle" title="Delete this comment..."><img src="../images/delete.png" alt="Delete"/></a></div>' +
					'</div></div>';
	 				
	 	$('#blogPosts').append (row);
   }
   console.log ('finished rendering');
}
// set UI elements to reflect state of 'blog is locked' flag
function setBlogLockedUI (isLocked)	{
	if (isLocked)	{
		$("#blogComment").prop('disabled', true);
		$("#blogSave").prop('disabled', true);
		$("#blogContributeContainer").hide(200);
		$("#blogLockButtonText").text("Unlock Discussion");
		$("#blogLockedMessage").show();
	}
	else	{
		$("#blogComment").prop('disabled', false);
		$("#blogSave").prop('disabled', false);
		$("#blogContributeContainer").show(200);
		$("#blogLockButtonText").text("Lock Discussion");
		$("#blogLockedMessage").hide();
	}
}
$("#lockUnlockBlog").click( function ()	{
	var bloggingAllowed = $("#isBloggingAllowed").val();
	console.log("lockUnlockBlog button clicked.  Flag is currently " + bloggingAllowed);
	
	if (bloggingAllowed == true || bloggingAllowed == "true")	{
		if (! confirm('This will lock the Virtual MDT discussion for this patient.\nFurther comments will not be allowed.\n\nPlease confirm you want to proceed:'))
			return false;
		
		$("#isBloggingAllowed").val(false);
		setBlogLockedUI (true);
		lockBlog();
	}
	else	{
		if (! confirm('This will unlock the Virtual MDT discussion for this patient.\nFurther comments will be allowed.\n\nPlease confirm you want to proceed:'))
			return false;
		
		$("#isBloggingAllowed").val(true);
		setBlogLockedUI (false);
		unlockBlog();
	}
});

// call the service to lock the discussion
function lockBlog()	{
	console.log('lock blog');
	$("#blogAction").val("lock");
	var csrfdata=document.getElementById("csrfparameterName").value;
	csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
	$.ajax({
		type: "POST",
		method: "POST",
		data: $("#blogForm").serialize(),
		url:  "virtualMeetingHandler.form?" + csrfdata,
		success: function(msg){   
			console.log ('ajax lock success');
			$("#blogComment").val('');
			showBlogSuccessMessage(msg,"Discussion is now locked.");
			renderBlogPosts(msg);
			console.log('end of ajax success');
		},
		error: function(msg){
			console.log('ajax lock error');
			showBlogErrorMessage("Error: it was not possible to lock the discussion.");
			
		}
	});

}

// call the service to unlock the discussion
function unlockBlog()	{
	console.log('lock blog');
	$("#blogAction").val("unlock");
	var csrfdata=document.getElementById("csrfparameterName").value;
	csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
	$.ajax({
		type: "POST",
		method: "POST",
		data: $("#blogForm").serialize(),
		url:  "virtualMeetingHandler.form?" + csrfdata,
		success: function(msg){   
			console.log ('ajax unlock success');
			$("#blogComment").val('');
			showBlogSuccessMessage(msg,"Discussion is now unlocked.");
			renderBlogPosts(msg);
			console.log('end of ajax success');
		},
		error: function(msg){
			console.log('ajax lock error');
			showBlogErrorMessage("Error: it was not possible to unlock the discussion.");
			
		}
	});
}
// Synchronous XHR request to check if blog is locked
// returns true if  locked
function checkLock ()	{
	let isLocked = true;
	console.log('check if blog is locked');
	$("#blogAction").val("checklock");
	var csrfdata=document.getElementById("csrfparameterName").value;
	csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
	$.ajax({
		type: "POST",
		method: "POST",
		async: false,
		data: $("#blogForm").serialize(),
		url:  "virtualMeetingHandler.form?" + csrfdata,
		success: function(msg){
			console.log ('ajax checklock success');
			isLocked = msg.locked;
			if (isLocked)
				showBlogErrorMessage("Another user has just locked this blog");

		},
		error: function( jqXHR, textStatus, errorThrown){
			showBlogErrorMessage(textStatus);
			console.log('textstatus ' + textStatus);
			console.log('errorThrown ' + errorThrown);
		},
		statusCode: {
			403: function() {
				showBlogErrorMessage("Your session has ended.  Please log in.");
				return;
			}
		}
	});
	console.log("isLocked: " + isLocked);
	return isLocked;
}

