(function()
{
	angular.module('annotations')
		.directive('claAnnotationPicker', ['$timeout', '$document', 'annotationService', pickerDirective]);

	function pickerDirective()
	{

		controller.$inject = ['$scope', '$timeout', '$document', 'annotationService'];

		return {
			restrict: 'E',

			scope: {},
			controllerAs: 'picker',

			/**
			 * Controller
			 */
			controller: controller,
			link: link,

			templateUrl: '/intranet/comments/html/ui/annotation_picker.html'
		};
	}

	var link = function(scope, element, attrs, controller)
	{
		controller.picker = element;

		controller.picker.on('annotation-picker-open', function($event, type, target)
		{
			controller.addPopup(type, target);
			$event.preventDefault();
			$event.stopPropagation();
		});
	};

	var controller = function ($scope, $timeout, $document, annotationService)
	{
		var ctrl = this;
		ctrl.currentSearch = '';

		ctrl.setCursorPos = function(elem, caretPos) {
			if (elem !== null) {
				if (elem.createTextRange) {
					var range = elem.createTextRange();
					range.move('character', caretPos);
					range.select();
				} else {
					if (elem.setSelectionRange) {
						elem.focus();
						elem.setSelectionRange(caretPos, caretPos);
					} else
						elem.focus();
				}
			}
		};

		// Intercept keypresses for special keys (arrows, etc)
		ctrl.onSearchKeyDown = function($event)
		{
			// Process various special keys
			switch ($event.keyCode)
			{
				case 27:  // Escape
				{
					//ctrl.display = ctrl.display.slice(0, ctrl.insertPos) + ctrl.currentSearch + ctrl.display.slice(ctrl.insertPos);
					//ctrl.insertPos += ctrl.currentSearch.length;
					ctrl.cancelPopup();
					break;
				}

				case 13:  // Enter
				{
					ctrl.useSelectedUser();
					break;
				}
				case 38:  // Up arrow
				{
					ctrl.popupSelectedUser = annotationService.selectAnotherUser(-1);
					$event.preventDefault();
					break;
				}
					break;
				case 40:  // Down arrow
				{
					ctrl.popupSelectedUser = annotationService.selectAnotherUser(1);
					$event.preventDefault();
					break;
				}
				case 8:  // Backspace
				case 46:  // Delete
				{
					if (ctrl.currentSearch.length === 1)
					{
						ctrl.currentSearch = '';
						ctrl.removePopup();
						$event.preventDefault();
						return;
					}

					$timeout(function()
					{
						ctrl.updateLookup();
					},0);
					break;
				}
			}
		};

		// Find out the real key code
		ctrl.onSearchKeyPress = function($event)
		{
			$timeout(function()
			{
				ctrl.updateLookup();
			}, 0);
		};

		// Stop clicks within the dropdown from closing the dropdown
		ctrl.onSearchClick = function($event)
		{
			$event.stopPropagation();
		};

		ctrl.documentClickHandler = function()
		{
			ctrl.cancelPopup();
			$document.off('click', ctrl.documentClickHandler);
		};

		// Show the dropdown list of users
		ctrl.addPopup = function(type, marker)
		{
			var cursorMarker = marker.find('.js-cursor-marker');
			ctrl.currentSearch = type;
			ctrl.picker.show();
			ctrl.updateLookup();
			var popup = ctrl.picker.find('.js-mention-popup');
			if (cursorMarker.length > 0)
			{
				var offset = cursorMarker.offset();
				popup.css('top', offset.top);
				popup.css('left', offset.left);
			}

			var search = ctrl.picker.find('#annotations-search');
			// Wait for $digest to let the popup appear
			$timeout(function()
			{
				$document.on('click', ctrl.documentClickHandler);
				search.focus();
				ctrl.setCursorPos(search[0], 1);
			}, 0);
		};

		// Hide the dropdown list of users
		ctrl.cancelPopup = function()
		{
			ctrl.popupSelectedUser = 0;
			ctrl.removePopup();
		};

		// Hide the dropdown list of users
		ctrl.removePopup = function()
		{
			ctrl.mentionLookups = [];
			ctrl.picker.hide();
			$document.off('click', ctrl.documentClickHandler);
			$timeout(function()
			{
				ctrl.picker.trigger('annotation-picker-closed', [ctrl.currentSearch, ctrl.popupSelectedUser]);
				ctrl.currentSearch = '';
			}, 0);
		};

		// gets users to fill the dropdown with
		ctrl.updateLookup = function()
		{
			var phrase = ctrl.currentSearch.slice(1);
			annotationService.getNames([phrase + ' '], function(result)
			{
				ctrl.mentionLookups = result;
				ctrl.popupSelectedUser = annotationService.selectedUser;
				if (ctrl.mentionLookups.length === 0)
					ctrl.removePopup();
			}, function(result)
			{
				console.log(result);
			});
		};

		ctrl.onMouseoverUser = function($event, user_id)
		{
			ctrl.popupSelectedUser = annotationService.selectUserById(user_id);
		};

		ctrl.onSearchUserClick = function($event)
		{
			ctrl.useSelectedUser();
		};

		// Inserts the users currently highlighted in the search dropdown into the text
		ctrl.useSelectedUser = function ()
		{
			if (ctrl.popupSelectedUser > 0)
			{
				var name = '';
				var userOffset = null;
				for (var i = 0; i < ctrl.mentionLookups.length; i++)
				{
					if (ctrl.mentionLookups[i].user_id == ctrl.popupSelectedUser)
					{
						userOffset = i;
						name = ctrl.mentionLookups[i].name;
					}
				}

				ctrl.currentSearch = '@' + name;
				ctrl.removePopup();
			}
		};
	};
}());