define("quickTicketControllers",
    [ "SHARED/jquery", "SHARED/uiCalendar", "SHARED/CalDateTimePicker",
        "SHARED/DateTimeFormatter", "SHARED/juzu-ajax", "/commons-extension/ckeditor/ckeditor.js" ], function($,
        timePicker, otherTimePicker, dateFormatter, jz) {
      var quickTicketCtrl = function($scope, $q, $timeout, $http, $filter, $window) {
        var ticketContainer = $('#ticketAddon');
        var deferred = $q.defer();

        $scope.newTicket = {};
        $scope.ticketLink = "";
        $scope.ticketLabel = "";
        $scope.fileUploading = false;
        $scope.submitInProgress = false;
        $scope.locale = eXo.env.portal.language;
        $scope.spaceGroupId = "";

        $scope.initForm = function () {
          $scope.submitInProgress = false;
        }

        $scope.loadBundles = function() {
          $http({
            method : 'GET',
            url : ticketContainer.jzURL('QuickTicketController.getBundle') + "&locale=" + eXo.env.portal.language
          }).then(function successCallback(data) {
            $scope.i18n = data.data;
            deferred.resolve(data);
          }, function errorCallback(data) {
            $scope.setResultMessage($scope.i18n.errorInitForm, "error");
          });
        }

        $scope.updateSettings = function() {
          console.log("Update portlet settings");
          $http({
            data : $scope.spaceGroupId,
            method : 'POST',
            headers : {
              'Content-Type' : 'application/json'
            },
            url : ticketContainer.jzURL('QuickTicketController.updateSettings')
          }).then(function successCallback(data) {
            $scope.i18n = data.data;
            deferred.resolve(data);
          }, function errorCallback(data) {
            $scope.setResultMessage($scope.i18n.errorInitForm, "error");
          });
        }


        $scope.saveTicket = function() {
        $scope.submitInProgress = true;
          $scope.newTicket.description = CKEDITOR.instances.requestDescription.getData();
          if ($scope.newTicket.description.replace('/<[^>]*>/gi', '').length == 0){
             $scope.setCKEditorError($scope.i18n.validateAddDescription,'error');
             return;
          } else {
             $scope.setCKEditorError('','');
          }

          $scope.setResultMessage($scope.i18n.savingTicket, "info");
          $http({
            data : $scope.newTicket,
            method : 'POST',
            headers : {
              'Content-Type' : 'application/json'
            },
            url : ticketContainer.jzURL('QuickTicketController.saveTicket')
          }).then(function successCallback(data) {
            if (data && data.data) {
              $scope.ticketLink = data.data.link[0];
              $scope.ticketLabel = data.data.label[0];
            } else {
              $scope.ticketLink = null;
              $scope.ticketLabel = null;
            }
            $scope.setResultMessage($scope.i18n.ticketSubmitted, "success");
            $scope.newTicket = null;
            $scope.newTicketForm = null;
            for(instance in CKEDITOR.instances ){
              CKEDITOR.instances[instance].updateElement();
              CKEDITOR.instances[instance].setData('');
            }
          }, function errorCallback(data) {
            $scope.setResultMessage($scope.i18n.ticketSubmitionError, "error");
          });
          $window.scrollTo(0, 0);
        }

        // function which set the result message with the given style
        $scope.setResultMessage = function(text, type) {
          $scope.resultMessageClass = "alert-" + type;
          $scope.resultMessageClassExt = "uiIcon"
              + type.charAt(0).toUpperCase() + type.slice(1);
          $scope.resultMessage = text;
        }

        $scope.setCKEditorError = function(text, type) {
          $scope.ckeditorErrorClass = "error";
          $scope.ckeditorErrorMessage = text;
        }

        $scope.fileUploadClick = function(element) {
          $scope.$apply(function($scope) {
            $(".ticketAddon input#fileToImport").click();
          });
        };

        $scope.prepareImportFile = function(element) {
          $scope.importFiles = element.files;
          if (!$scope.importFiles || !$scope.importFiles.length) {
            $scope.importFiles = null;
            $scope.setResultMessage($scope.i18n.noSelectedFile, "error");
            return;
          }

          $(".ticketAddon .uiAction").addClass("resources-loader");

          console.log("length = " + $scope.importFiles.length);
          if($scope.importFiles.length > 3) {
            $scope.importFiles = null;
            $scope.setResultMessage($scope.i18n.validateMaxSelectedFile, "warning");
            return;
          }
          var form = new FormData();
          for (i = 1; i <= $scope.importFiles.length; i++){
            var importFile = $scope.importFiles[i - 1];
            console.log("importFile = " + importFile);
            console.log("name = " + importFile.name);
            console.log("size = " + importFile.size);
            if(importFile.size > 10485760) {
              $scope.importFiles = null;
              $scope.setResultMessage($scope.i18n.validateMaxSelectedFileSize, "warning");
              return;
            }
            form.append("file" + i, importFile);
          }

          $scope.fileUploading = true;
          $scope.setResultMessage($scope.i18n.analyzingFile, "info");
          $http({
            url : ticketContainer.jzURL("QuickTicketController.prepareImportFile"),
            data : form,
            method : 'POST',
            headers : {
              'Content-Type' : undefined
            },
            transformRequest : function(data) {
              return data;
            }
          }).success(function(dataList) {
            $scope.fileUploading = false;
            $scope.setResultMessage("", "info");

            $(".ticketAddon .uiAction").removeClass("resources-loader");
          }).error(function(data) {
            $scope.fileUploading = false;
            $scope.importFiles = null;
            $(".ticketAddon .uiAction").removeClass("resources-loader");
            $scope.setResultMessage($scope.i18n.errorUploadingFile, "error");
          });
        }
        $scope.loadBundles();
        $scope.initForm();
        var extraPlugins = 'simpleLink,selectImage,hideBottomToolbar';
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        if (windowWidth > windowHeight && windowWidth < 768) {
        // Disable suggester on smart-phone landscape
          extraPlugins = 'simpleLink,selectImage';
        }
        CKEDITOR
            .replace(
                'requestDescription',
                {
                  customConfig: '/commons-extension/ckeditorCustom/config.js',
                  extraPlugins: extraPlugins,
                  removePlugins: 'image',
                  toolbar:'Basic',
                  height : '200px',
                  contentsCss : ['/commons-extension/ckeditor/contents.css'],
                  enterMode : CKEDITOR.ENTER_P,
                  forceEnterMode : false,
                  shiftEnterMode : CKEDITOR.ENTER_BR
                });

        $scope.refreshController = function() {
          try {
            $scope.$apply();
            $scope.$digest();
          } catch (excep) {
            // Nothing here
          }
        };

        $('#ticketAddon').css('visibility', 'visible');
        $(".ticketLoadingBar").remove();
      };
      return quickTicketCtrl;
    });