define(['cla_angular', './dropbox.html', '../../../../../web/intranet/js/dropbox_dialog.js'], function (angular, template, fuuClass) {
	var moduleName = 'cla.core.dropbox';
	try {
		var module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		var module = angular.module(moduleName, []);
	}

	module.directive('claDropbox', Dropbox);



	function Dropbox() {

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

            this.$onInit = function() {
                ctrl.options = {
                    files: [],
                    multiple: false
                };

                if (ctrl.multiple === 'true')
                    ctrl.options.multiple = true;

                $timeout(function () {
                    ctrl.fuu_obj = new fuuClass(ctrl.options, ctrl.context, true);

                    angular.element( "body" ).on("dd_change", function() {
                        ctrl.sync();
                    });
                }, 0);

                ctrl.ngModel.clearFiles = function (files) {
                    files.forEach(function(element) {
                        ctrl.fuu_obj._removeFile(element);
                    });
                }
            };

			ctrl.sync = function(){

				ctrl.list = angular.element(document.getElementsByClassName("dd_selected_files"));
				// ctrl.mml = angular.element(document.getElementById('myMenuList'));
				ctrl.ngModel.files.length = 0;
				ctrl.list.find('li').each(function( index ) {
					var file_name = angular.element(this).text().trim();
					var hash = '';
					angular.element(this).find('input').each(function () {
						hash = angular.element(this).val();
					});
					ctrl.ngModel.files.push({hash: hash, file_name: file_name});
				});


				$timeout(function () {
					$scope.$digest();

				}, 0);

				ctrl.ngModel.callBack();
			};

			ctrl.clickFile = function ($event) {

				var self = this;
				$timeout(function () {
					self.fuu_obj._returnFileNameFromModalWindow($event.target);
				}, 0);

				$event.preventDefault();
			};

			ctrl.openUploaded = function ($event) {
				angular.element(document).ajaxComplete(function () {
					angular.element(document).unbind('ajaxComplete');

					var file_content = angular.element('#browseUploaded .modal-body').html();
					$scope.$apply(function() {
						angular.element('#browseUploaded .modal-body').html($compile(file_content)($scope));
					});

				});

				this.fuu_obj._openSelectModalWindow();
				$event.preventDefault();
			};
		};

		controller.$inject = ['$scope', '$timeout', '$compile'];
			// ctrl.$setViewValue
		return {
			controller: controller,
			bindToController: true,
			controllerAs: 'ctrl',
			restrict: 'E',
			require: '^ngModel',
			templateUrl: template,
			scope: {
				ngModel: '=',
				context: '@',
				multiple: '@'
			}
		};
	}
});
