(function()
{
	var moduleName = 'fileupload';
	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	module
    .directive('claFileUpload', ['$rootScope', '$timeout', fileUploadDirective]);

	function fileUploadDirective($rootScope, $timeout)
	{
		var TYPE_FILE = 3;
		var SERVER_PATH = '/intranet/comments/fileupload.php';
		controller.$inject = ['$scope', '$timeout'];

		return {
			restrict: 'E',

			scope: {},
			bindToController: {
				files: '=', // 2 way binding
				controlToken: '=' // 2 way binding
			},
			controllerAs: 'cfu',

			/**
			 * Controller
			 */
			controller: controller,

			template: '<div id="comments_uploader-' + $rootScope.$id + '"></div>'
		};

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

            this.$onInit = function() {
                $timeout(function()
                {
                    var uploaderElement = angular.element("#comments_uploader-" + $rootScope.$id);
                    if (uploaderElement.length === 0)
                        return;

                    ctrl.uploader = new qq.FileUploader({
                        element: uploaderElement[0],
                        action: SERVER_PATH,
                        debug: ctrl.showQQDebug
                    });

                    /**
                     * File upload start
                     *
                     * @param id
                     */
                    ctrl.uploader._options.onSubmit = function (id)
                    {
                        ctrl.files[id] = {
                            started: true,
                            done: false,
                            cancelled: false,
                            progress: 0
                        };

                        // execute angular digest loop
                        $scope.$apply();
                    };

                    /**
                     * Update progress
                     *
                     * @param id
                     * @param name
                     * @param loaded
                     * @param total
                     */
                    ctrl.uploader._options.onProgress = function (id, name, loaded, total)
                    {
                        ctrl.files[id].progress = loaded / total;

                        // execute angular digest loop
                        $scope.$apply();
                    };

                    /**
                     * File upload success
                     *
                     * @param id
                     * @param name
                     * @param response
                     */
                    ctrl.uploader._options.onComplete = function (id, name, response)
                    {
                        if( ctrl.files[id].progress >= 1 ) {
                            ctrl.files[id].done = true;
                        }

                        ctrl.files[id].response = response;
                        ctrl.files[id].response.type = TYPE_FILE; // PHP Attachment::TYPE_FILE

                        // execute angular digest loop
                        $scope.$apply();
                    };

                    // we can't just delete file uploads when they are cancelled as the progress update will cause a console error.
                    // So we mark them as cancelled and just ignore them when the comment is submitted
                    ctrl.uploader._options.onCancel = function(id, name)
                    {
                        ctrl.files[id].cancelled = true;
                        return true;
                    };
                },0);

                ctrl.token = ctrl.controlToken || {};
                ctrl.token.resetFiles = function()
                {
                    var uploaderElement = angular.element("#comments_uploader-" + $rootScope.$id);
                    if (uploaderElement.length === 0)
                        return;

                    // Save uploader handlers
                    var options = ctrl.uploader._options;

                    ctrl.uploader = new qq.FileUploader({
                        element: uploaderElement[0],
                        action: SERVER_PATH,
                        debug: ctrl.showQQDebug
                    });

                    // Restore uploader handlers
                    ctrl.uploader._options = options;

                    ctrl.files.length = 0;
                }
            };

			ctrl.showQQDebug = false;
			ctrl.uploader = null;
		}
	}
}());
