(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);
		};

		//get Cursor offset in order to set the @ mention dropdown in the correct position
		ctrl.getCursorWindowOffset = function(textarea) {
			var selectionStart = textarea.selectionStart;

			var div = document.createElement('div');
			document.body.appendChild(div);

			// Copy textarea styles
			var style = window.getComputedStyle(textarea);
			div.style.position = 'absolute';
			div.style.visibility = 'hidden';
			div.style.whiteSpace = 'pre-wrap';
			div.style.wordWrap = 'break-word';
			div.style.width = style.width;
			div.style.font = style.font;
			div.style.padding = style.padding;
			div.style.border = style.border;
			div.style.lineHeight = style.lineHeight;
			div.style.overflow = 'hidden';

			var text = textarea.value.substring(0, selectionStart);
			div.textContent = text;

			var span = document.createElement('span');
			span.textContent = '\u200b';
			div.appendChild(span);

			div.scrollTop = textarea.scrollTop;
			div.scrollLeft = textarea.scrollLeft;

			var top = span.offsetTop - textarea.scrollTop;
			var left = span.offsetLeft - textarea.scrollLeft;

			var rect = textarea.getBoundingClientRect();

			var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
			var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;

			var windowTop = rect.top + top + scrollTop;
			var windowLeft = rect.left + left + scrollLeft;

			document.body.removeChild(div);

			return { top: windowTop, left: windowLeft };
		}

		// Show the dropdown list of users
		ctrl.addPopup = function(type, marker)
		{
			var cursorMarker = marker.find('.js-cursor-marker');
			var textarea = marker.prev().find('textarea')[0];

			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', ctrl.getCursorWindowOffset(textarea).top - 6);
				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();
			}
		};
	};
}());
