/* Set up logging: Log through the integration controller
* if it exists; otherwise, log through the console
*/

if (typeof window.webkit == "undefined") {
	integrationController = null
	log = function(i) { console.log(i) }
} else {
	log = function (m) {
		window.webkit.messageHandlers.KSLog.postMessage(m)
	}
	
	integrationController = {
		log: log,
		openAppleHelpAnchor_: function (anchor) {
			window.webkit.messageHandlers.KSCall.postMessage(`openAppleHelpAnchor:\n${anchor}`)
		},
		runUninstallScript_: function (name) {
			window.webkit.messageHandlers.KSCall.postMessage(`runUninstallScript:\n${name}`)
		},
		runScript_: function (name) {
			window.webkit.messageHandlers.KSCall.postMessage(`runScript:\n${name}`)
		},
		runSampleScript_: function (name) {
			window.webkit.messageHandlers.KSCall.postMessage(`runSampleScript:\n${name}`)
		},
		runUpdateScript_: function (name) {
			window.webkit.messageHandlers.KSCall.postMessage(`runUpdateScript:\n${name}`)
		},
		openPath_: function (path) {
			window.webkit.messageHandlers.KSCall.postMessage(`openPath:\n${path}`)
		},
		shouldRunScriptForInstallButtonInSection_toolName_: function(section, toolName) {
			return window.webkit.messageHandlers.KSReply.postMessage(`shouldRunScriptForInstallButtonInSection:toolName:\n${section}\n${toolName}`)
		},
	}
	
	$(document).ready( () => {
		// disable context menu unless in areas where we want them (e.g. the email field) so the reload entry doesn't appear)
		$('body').contextmenu( (evt) => { evt.preventDefault() })

		window.webkit.messageHandlers.KSCall.postMessage("integrationJSScriptReady");

		// quick tests
		//		log("document loaded")
	})
}

function switched(event) {
	var element = event.currentTarget;
	
	var identifier = $(element).attr('id');
	switchToToolWithIdentifier(identifier);
	
	return false;
}

function switchToToolWithIdentifier(identifier)
{
	var elementToSelectSelector = "#" + identifier;
	var bodySelector = elementToSelectSelector + '-body';
	var isSelected = $(elementToSelectSelector).hasClass("selected");
	
	if (isSelected == false) {
		// hide all the content on the right.
		$("*[data-content]").addClass("hidden");
		
		//  unselect all items on the left
		$("li").removeClass("selected");
		// select the new selection on the left
		$(elementToSelectSelector).addClass("selected");
		
		// show the appropriate content on the right
		$(bodySelector).removeClass("hidden");
		var element = document.getElementById(identifier + '-body')
		if (element) {
			element.scrollIntoView(true);
		}
	}
}

async function shouldRunScriptForInstallButtonInSection(theSectionName, theToolName) {
	if (integrationController) {
		return integrationController.shouldRunScriptForInstallButtonInSection_toolName_(theSectionName, theToolName);
	}
	return true;
}

function runScriptForStep(step) {
	
	var toolName = $(step).attr("data-install-tool");
	var sectionName = $(step).attr("id");
	if (sectionName == undefined)
	sectionName = "";
	
				// Determine what kind of action should be taken --
				// If the step has the 'installed' class, uninstall it
				// if possible (otherwise do nothing). If it doesn't
				// have that class, do nothing
				if ($(step).hasClass("sample")) {
					if (integrationController) {
						integrationController.runSampleScript_(toolName);
					} else {
						log("This would now open the sample for " + toolName + ", but there is no controller available");
					}
				} else if ($(step).hasClass("outdated")) {
					if (integrationController) {
						integrationController.runUpdateScript_(toolName);
					} else {
						log("This would now install " + toolName + ", but there is no controller available");
						markAsInstalled(toolName);
					}
				} else if ($(step).hasClass("installed")) {
					var uninstallTool = $(step).attr("data-uninstall-tool");
					if (uninstallTool == null) {
						// There doesn't seem to be anything to uninstall. do nothing.
						return false;
					}
					if (uninstallTool == "")
					uninstallTool = toolName;

					if (integrationController) {
						integrationController.runUninstallScript_(uninstallTool);
					} else {
						log("This would now uninstall " + uninstallTool + ", but there is no controller");
						markAsUninstalled(uninstallTool);
					}
				}  else {
					if (integrationController) {
						integrationController.runScript_(toolName);
					} else {
						log("This would now install " + toolName + ", but there is no controller available");
						markAsInstalled(toolName);
					}
				}

}

function openPath(path) {
	if (integrationController)
	integrationController.openPath_(path);
	else
	log("This would open the path " + path + " in TextEdit.");
}

$(document).ready(function() {
	// Convert buttons to jQuery-UI buttons to get proper mouse tracking
	$(".button").button();
	
	// convert these to jquery-ui buttons to get better :active tracking.
	$("#leftcol nav ul li.entry").button();
	// This removes the ability for the element to allow selection of text outside of itself
	// For example, mouse down on the element, drag outside into the main area and if there's
	// selectable text there, it'll get selected. This stops that.
	$("#leftcol nav ul li.entry").each(function(index, element){
		element.onmousedown = function(event) {
			return false;
		}
	});
	
	// Mark all headers as collapsible
	$("li.entry").click(switched);
	
	// Allow special links to switch categories as well
	$("a.entry").click(switched);

	// Add a 'with-code' class to all elements that have a code block
	$(".step:has(code)").addClass("with-code")

	//	$(".hidden").each(function(i, element) { $(element).css("display", "none"); });
	// Add a click handler for every step with an install step
	$(".step[data-install-tool]").each(function(index, step) {
		
		var buttons = $(step).not(".missingRequirements").children(".expl").children(".button");
		buttons.click(function() { runScriptForStep(step); });

	});

	// Add a different click handler for every step with an open path
	$(".button[data-path]").each(function(index, item) {
		$(item).click(function() { openPath($(item).attr("data-path")); })
	});
	var hiddenKsdiffContent = $("#ksdiff-manual-install");
	var switchKsdiffContent = $("#ksdiff-manual-toggle");
	switchKsdiffContent.on( "click", function(event) {
	  switchKsdiffContent.fadeOut();
	  hiddenKsdiffContent.slideDown();
	});

	var hiddenGitContent = $("#git-manual-install");
	var switchGitContent = $("#git-manual-toggle");
	switchGitContent.on( "click", function(event) {
	  switchGitContent.fadeOut();
	  hiddenGitContent.slideDown();
	});
});


/* Callbacks from Objective-C */
function markAsInstalled(toolName) {
	//log(toolName + " is marked as installed");

	var elements = $("*[data-install-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).addClass("installed");
		$(element).removeClass("outdated");
	});
	
	var elements = $("*[data-update-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("visible");
	});
	
	// Set the status for this tool.
	var buttons = $("*[data-status-tool='" + toolName.replace(/-.*/, "") + "']")
	buttons.each(function(index, item) {
		$(item).addClass("visible");
		$(item).removeClass("outdated");
	});
	
	// updateInstallUninstallScriptLocations();
}

function markAsOutdated(toolName) {
	//log(toolName + " is marked as outdated");

	var elements = $("*[data-install-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("installed");
		$(element).addClass("outdated");
	});
	
	var elements = $("*[data-update-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).addClass("visible");
	});
	
	// Set the status for this tool.
	var buttons = $("*[data-status-tool='" + toolName.replace(/-.*/, "") + "']")
	buttons.each(function(index, item) {
		$(item).addClass("visible");
		$(item).addClass("outdated");
	});
	
	// updateInstallUninstallScriptLocations();
}

function markAsUninstalled(toolName) {
	//log(toolName + " is marked as uninstalled");

	var elements = $("*[data-install-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("installed");
	});
	
	// Set the status for this tool.
	var VCS = toolName.replace(/-.*/, "");

	// Find the container that has this tool
	var tools = $("li:has(div.status[data-status-tool='" + VCS + "'])")
	tools.each(function(index, tool) {
		// Only remove the checkmark if there are no other things that have
		// installed this tool
		if ($("div.step.installed[data-install-tool^=" + VCS + "]").length == 0) {
			$(tool).find("div.status").removeClass("visible");
		}
	});
	
	var elements = $("*[data-update-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("visible");
	});
	
	// updateInstallUninstallScriptLocations();
}

function markAsMissingSystemRequirements(toolName) {
	//log(toolName + " is marked as missing system requirements");

	var elements = $("*[data-install-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("sample");
		$(element).addClass("missingRequirements");

	});
	
	// Set the status for this tool.
	var VCS = toolName.replace(/-.*/, "");

	// Find the container that has this tool
	var tools = $("li:has(div.status[data-status-tool='" + VCS + "'])")
	tools.each(function(index, tool) {
		// Only remove the checkmark if there are no other things that have
		// installed this tool
		if ($("div.step.installed[data-install-tool^=" + VCS + "]").length == 0) {
			$(tool).find("div.status").addClass("visible");
			$(tool).find("div.status").addClass("missingRequirements");
		}
	});
	
	var elements = $("*[data-update-tool='" + toolName + "']")
	elements.each(function(index, element) {
		$(element).removeClass("visible");
	});
}

function openAppleHelpAnchor(anchorName) {
	integrationController.openAppleHelpAnchor_(anchorName);
	return false;
}
