/**
 * Part of the Collection Workflow Integration System (CWIS)
 * Copyright 2015 Edward Almasy and Internet Scout Research Group
 * http://scout.wisc.edu/
 */

/**
 * callback one the pop when someone click the "cancel" button (or the overlay).
 * remove the popup from the page
 * @param event: the event that trigger this callback
 */
function TransferFolderCancleButtonDidClicked(event) {
	ClosePopupUI();
}

/**
 * callback on the popup when someone click the "transfer" button
 * sends a ajax request to backend to perform the folder transfer
 * @param event: the event that triggered this callback
 */
function TransferFolderConfirmButtonDidClicked(event) {
	var folderID = event.target.getAttribute("folderid");
	var trimmed = $.trim($("#cw-folders-transfer-folder-popup-uname-field").val());

	if (trimmed.length != 0) {
		// send out ajax request
		$.ajax({
			type: "POST",
			url: CWIS_BASE_URL + "index.php?P=P_Folders_TransferFolders&FID=" + folderID,
			data: {username: trimmed},
			dataType: "html",
			success: function(data) {
				var result = JSON.parse(data);

				if (result.status.state != "OK") {
					// display error message
					DisplayErrorMessage(result.status.message);
				} else {
					// display success message
					DisplaySuccessMessage(result.status.message);
					setTimeout(function(){
						window.location.reload();
					}, 1500);
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
            	console.log(textStatus, errorThrown);
            }
		});
	}
}

/**
 * display success message in popup upon receiving success message from back end
 * @param message: the success message to display
 */
function DisplaySuccessMessage(message) {
	// first remove error message if there is any
	if ($("#cw-folders-transfer-folder-popup-error").length != 0) {
		$("#cw-folders-transfer-folder-popup-error").remove();
	}

	// add success message if needed
	if ($("#cw-folders-transfer-folder-popup-success").length == 0) {
		var success = document.createElement("div");
		success.id = "cw-folders-transfer-folder-popup-success";
		$("#cw-folders-transfer-folder-popup-body").append(success);
	}

	$("#cw-folders-transfer-folder-popup-success").text(message);
}

/**
 * display error message in popup upon receiving error message from back end
 * @param message: the error message to display
 */
function DisplayErrorMessage(message) {
	// first remove success message if there is any
	if ($("#cw-folders-transfer-folder-popup-success").length != 0) {
		$("#cw-folders-transfer-folder-popup-success").remove();
	}

	// add error message if needed
	if ($("#cw-folders-transfer-folder-popup-error").length == 0) {
		var error = document.createElement("div");
		error.id = "cw-folders-transfer-folder-popup-error";
		$("#cw-folders-transfer-folder-popup-body").append(error);
	}

	$("#cw-folders-transfer-folder-popup-error").text("Error: " + message);
}

/**
 * close (remove) the main popup UI
 */
function ClosePopupUI() {
	if ($("#cw-folders-transfer-folder-popup").length) {
		$("#cw-folders-transfer-folder-overlay").remove();
		$("#cw-folders-transfer-folder-popup").remove();
	}
}

/**
 * display (create and insert) the main popup UI
 * @param folderID: the id of the folder to transfer
 * @param folderName: the name of the folder to transfer
 */
function DisplayPopupUI(folderID, folderName) {
	if($("#cw-folders-transfer-folder-overlay").length || $("#cw-folders-transfer-folder-popup").length) {
		return;
	}

	var overlay = document.createElement("div");
	overlay.id = "cw-folders-transfer-folder-overlay";

	var popup = document.createElement("div");
	popup.id = "cw-folders-transfer-folder-popup";
	popup.setAttribute("folderid", folderID);

	$("body").append(overlay);
	$("body").append(popup);

	$("#cw-folders-transfer-folder-popup").html(
		"<div id=\"cw-folders-transfer-folder-popup-title-bar\">" +
			"<h1 id=\"cw-folders-transfer-folder-popup-title\">Transfer Folder \"" + folderName + "\"</h1>" +
		"</div>" +
		"<div id=\"cw-folders-transfer-folder-popup-body\">" +
			"<p id=\"cw-folders-transfer-folder-popup-description\">"+
				"Please enter the user name of the user whom you want to transfer this folder (\"" + folderName + "\") to.<br>" +
				"<b>Caution</b>: This operation cannot be undone." +
			"</p>" +
			"<label id=\"cw-folders-transfer-folder-popup-uname-label\">User Name:</label>" +
			"<input id=\"cw-folders-transfer-folder-popup-uname-field\" type=\"text\" name=\"cw-folders-transfer-folder-popup-uname\">" +
		"</div>" +
		"<div id=\"cw-folders-transfer-folder-popup-button-group\">" +
			"<button class=\"cw-button cw-button-elegant\" id=\"cw-folder-transfer-folder-button-confirm\" folderid=\"" + folderID + "\" foldername=\"" + folderName + "\">Transfer</button>" +
			"<button class=\"cw-button cw-button-elegant\" id=\"cw-folder-transfer-folder-button-cancel\" folderid=\"" + folderID + "\" foldername=\"" + folderName + "\">cancel</button>" +
		"</div>");
	$("#cw-folder-transfer-folder-button-confirm").click(TransferFolderConfirmButtonDidClicked);
	$("#cw-folder-transfer-folder-button-cancel").click(TransferFolderCancleButtonDidClicked);
	$("#cw-folders-transfer-folder-overlay").click(TransferFolderCancleButtonDidClicked);

	// enable auto-complete for user name input
	$("#cw-folders-transfer-folder-popup-uname-field").autocomplete({
		appendTo: "#cw-folders-transfer-folder-popup-body",
		source: function(request, response) {
			$.get(CWIS_BASE_URL + "index.php?P=P_Folders_UserNameSearchCallback&SS=" + request.term, {
			}, function(data){
				var result = JSON.parse(data);
				response(result);
			});
		},
		select: function(event, ui) {
			$("#cw-folders-transfer-folder-popup-uname-field").val(ui.item.Value);
			return false;
		},
		focus: function(event, ui) {
			$("#cw-folders-transfer-folder-popup-uname-field").val(ui.item.Value);
			return false;
		},
	}).data("ui-autocomplete")._renderItem = function(ul, item) {
		return $("<li></li>")
			.data("item.autocomplete", item)
			.append(item.Label)
			.appendTo(ul);
	};
}

/**
 * callback on ManageFolders page when someone clicked "Transfer Folder" button
 * Gather folderID and folderName and display the popup
 * @param event: the event that triggered this callback
 */
function TransferFolderButtonDidClicked(event) {
	event.preventDefault();
	var folderID = event.target.getAttribute("data-folderid");
	var folderName = event.target.getAttribute("data-foldername");
	DisplayPopupUI(folderID, folderName);
}

$(document).ready(function() {
	$(".cw-folder-transfer-folder-button").click(TransferFolderButtonDidClicked);
});