define(['cla_angular', 'folder_picker', './folder_picker.html', '../lmsg.directive.js'], function (angular, folderPickerClass, template) {
	var moduleName = 'cla.core.folder_picker';
	try {
		var module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		var module = angular.module(moduleName, ['cla.core.lmsg']);
	}

	module.directive('claFolderPicker', folderPicker);

	function folderPicker() {

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

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

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

            this.$onInit = function() {
                ctrl.id = 'folderPicker' + $scope.unique;
                ctrl.folderId = $scope.ngModel;
                ctrl.folderName = $scope.folderName;
            };
		}

		function link(scope, iElement, iAttrs, ctrl) {

			scope.id = 'folderPicker' + scope.unique;

			scope.init = function()
			{
				var folderPicker = new folderPickerClass(scope.id, '');
			};

			scope.onChange = function(value)
			{
				scope.ngModel = parseInt(value);
				ctrl.$setViewValue(scope.ngModel);
			};

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

				scope.init();
			};
		}
	}
});
