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.uploadIds = [];

        $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.newTicket.uploads = $scope.uploadIds;
          $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;
            $scope.uploadIds = [];
            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.uploadFile = function(data) {

          const MAX_RANDOM_NUMBER = 100000;
          const uploadId = Math.round(Math.random() * MAX_RANDOM_NUMBER);

            fetch(`/portal/upload?uploadId=${uploadId}&action=upload`, {
              method: 'POST',
              credentials: 'include',
              body: data
            }).then(response => {
                    $scope.uploadIds.push(uploadId);
                    $scope.fileUploading = false;
             })
        };

        $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");
          if($scope.importFiles.length > 3) {
            $scope.importFiles = null;
            $scope.setResultMessage($scope.i18n.validateMaxSelectedFile, "warning");
            return;
          }
		  $scope.fileUploading = true;
          $scope.setResultMessage($scope.i18n.analyzingFile, "info");

          [...$scope.importFiles].forEach((file) => {
              var formData = new FormData();
            formData.append('data', file, file.name);
            $scope.uploadFile(formData)

          });
		  $scope.setResultMessage("", "info");
          $(".ticketAddon .uiAction").removeClass("resources-loader");
        }
        $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;
    });