define(['cla_angular', './image_picker.html', 'image_dialog', 'jquery', '../../../../../web/assets/styles/components/fileuploader.css'], function (angular, template, imageDialog, $) {
	var moduleName = 'cla.core.image_picker';
	try {
		var module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		var module = angular.module(moduleName, []);
	}

	module.directive('claImagePicker', imagePicker);

	imagePicker.$inject = ['$timeout'];
	function imagePicker($timeout) {

		controller.$inject = ['$scope'];

		return {
			controllerAs: 'ctrl',
			controller: controller,
			link: link,
			restrict: 'E',
			require: '^ngModel',
			templateUrl: template,
			scope: {
				ngModel: '=',
				unique: '@',
				control: '='
			}
		};

		function controller($scope) {
			var ctrl = this;

            this.$onInit = function() {
                if ($scope.ngModel === null)
                {
                    $scope.ngModel = {
                        id: null,
                        url: '',
                        new_image: '',
                        new_url: ''
                    };
                } else {
                    $scope.ngModel.url = $scope.ngModel.url ? $scope.ngModel.url : '';
                    $scope.ngModel.new_url = $scope.ngModel.new_url ? $scope.ngModel.new_url : '';
                }
            };

			ctrl.isTempFile = function()
			{
				return $scope.ngModel.new_image !== '';
			};

			ctrl.hasImage = function()
			{
				return (($scope.ngModel.url.length + $scope.ngModel.new_url.length) > 0);
			};

			ctrl.imageUrl = function()
			{
				var url = $scope.ngModel.new_url;

				if (url === '')
					url = $scope.ngModel.url;

				return url;
			}
		}

		function link(scope, iElement, iAttrs, ctrl) {
			function onSave(data)
			{
				scope.ngModel.new_image = data.img_tmp_name;
				scope.ngModel.new_url = data.img_tmp_url;
				ctrl.$setViewValue(scope.ngModel);
			}
			// Create global var that image_dialog needs
			eval('window.ICParams_' + scope.unique + ' = {\
						callback: ' + onSave + ',\
						minWidth: 0,\
						minHeight: 0,\
						aspectRatio: 0,\
						lockAspectRatio: 0,\
						fieldName: scope.unique };');

			scope.name = scope.unique;

			function init(unique)
			{
				var cropTool = angular.element('#ImageCropComponent_' + unique);
				if (cropTool.length === 0)
					return;

				// Disable the settings auto-close while the crop tool is open
				cropTool.off('CropToolModalOpen');
				cropTool.on('CropToolModalOpen', function()
				{
                    if (typeof window.cla.pagesEdit !== 'undefined')
						window.cla.pagesEdit.popoverAutoClose = false;
				});
				cropTool.off('CropToolModalClose');
				cropTool.on('CropToolModalClose', function()
				{
					// Reinitialize the image dialog
					imageDialog.init(cropTool[0]);

                    if (typeof window.cla.pagesEdit !== 'undefined')
                    {
						// Delay slightly to avoid the settings closing due to this click
						$timeout(function()
						{
							window.cla.pagesEdit.popoverAutoClose = true;
						}, 0);
					}
				});

				imageDialog.init(cropTool[0]);
			}


			$timeout(function()
			{
				init(scope.unique);
			}, 0);

			scope.internalControl = scope.control || {};
			scope.internalControl.reset = function()
			{
				// Rebind the model. This shouldn't be needed but it never gets updated once reset otherwise
				ctrl.$setViewValue(scope.ngModel);

				$timeout(function()
				{
					init(scope.unique);
				}, 0);
			};
		}
	}
});
