define("ticketAdminControllers", [ "SHARED/jquery", "SHARED/juzu-ajax"], function($) {
  var csCtrl = function($scope, $q, $timeout, $http, $filter, PagerService) {
    var csContainer = $('#csAddon');
    var deferred = $q.defer();

    $scope.tickets = [];
    $scope.assignees;
    $scope.severities = [];
    $scope.statuses = [];
    $scope.ticketTypes = [];
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.def = '';
    $scope.selectedFilter='myopentickets';
    $scope.ticketToDelete = {};

    $scope.orderByField = 'updateDate';
    $scope.reverseSort = false;
    $scope.ticket = {};

    $scope.vm = this;
    $scope.vm.pager = {};
    $scope.vm.setPage = setPage;

    function setPage(page) {
      var tickets = $filter('filter')($scope.tickets, $scope.def);
      tickets = $filter('orderBy')(tickets, $scope.orderByField, $scope.reverseSort);

      // get pager object from service
      $scope.vm.pager = PagerService.GetPager(tickets.length, page);

      // get current page of items
      $scope.vm.items = tickets.slice($scope.vm.pager.startIndex, $scope.vm.pager.endIndex + 1);
    }

    $scope.setResultMessage = function(text, type) {
      $scope.resultMessageClass = "alert-" + type;
      $scope.resultMessageClassExt = "uiIcon" + type.charAt(0).toUpperCase()
          + type.slice(1);
      $scope.resultMessage = text;
    }

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

    $scope.loadTickets = function(selectedFilter) {
      $http({
        method : 'GET',
        url : csContainer.jzURL('TicketAdministrationController.getAllTickets') + "&filter=" + selectedFilter
      }).then(function successCallback(data) {
        $scope.setResultMessage(data, "success");
        deferred.resolve(data);
        $scope.tickets = data.data;
        $scope.vm.setPage(1);
        $timeout(function() {
          $scope.setResultMessage("", "info")
        }, 3000);
      }, function errorCallback(data) {
        $scope.setResultMessage(data, "error");
      });

      return deferred.promise;
    };

    $scope.editTicket = function(modifiedTicket){
       $scope.ticket = modifiedTicket;
       $scope.loadSeverities($scope.ticket);
       $scope.loadTicketTypes();
    }

    $scope.getDisplayName = function(username){
      for (var i = 0; i < $scope.assignees.length; i++) {
        if ($scope.assignees[i].userName === username) {
           return $scope.assignees[i].displayName;
        }
      }
      return $scope.i18n.empty;
    }


    $scope.saveTicket = function(ticket) {
      $http({
        data : ticket,
        method : 'POST',
        headers : {
         'Content-Type' : 'application/json'
        },
        url : csContainer.jzURL('TicketAdministrationController.saveTicket')
        }).then(function successCallback(data) {
          ticket.id = data.data.id;
        }, function errorCallback(data) {
          $scope.setResultMessage($scope.i18n.ticketSubmitionError, "error");
        });
    }

    $scope.loadAssignees = function(ticket) {
       ticket = $scope.ticket;
       $http({
          data : ticket,
          method : 'POST',
          headers : {
            'Content-Type' : 'application/json'
          },
          url : csContainer.jzURL('TicketAdministrationController.getSupportUsernames')
       }).then(function successCallback(data) {
           $scope.assignees = data.data;
           $timeout(function() {
                $scope.setResultMessage("", "info")
           }, 3000);
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

    $scope.loadSeverities = function(ticket) {
       $http({
           data : ticket,
           method : 'POST',
           headers : {
             'Content-Type' : 'application/json'
           },
           url : csContainer.jzURL('TicketAdministrationController.getSeverities')
       }).then(function successCallback(data) {
           $scope.severities = data.data;
           $timeout(function() {
                $scope.setResultMessage("", "info")
           }, 3000);
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

    $scope.loadTicketTypes = function() {
       $http({
          url : csContainer.jzURL('TicketAdministrationController.getTicketTypes')
       }).then(function successCallback(data) {
           $scope.ticketTypes = data.data;
           $timeout(function() {
                $scope.setResultMessage("", "info")
           }, 3000);
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

    $scope.loadStatuses = function (){
       $http({
         url : csContainer.jzURL('TicketAdministrationController.loadStatuses')
      }).then(function successCallback(data) {
          $scope.statuses = data.data;
          $timeout(function() {
               $scope.setResultMessage("", "info")
          }, 3000);
      },function errorCallback(data) {
          $scope.setResultMessage(data, "error");
      });
    }

    $scope.getStatusSuccessors = function(ticket,status) {
        if(!status){
           status = 'open';
        }
        $scope.statuses['INCIDENT'][0].successors[0]
        var flowStatuses = $scope.statuses[ticket.type];
        for (var i=0 ; i<flowStatuses.length ; i++){
          if(flowStatuses[i].state === status){
            return flowStatuses[i].successors;
          }
        }
        return ['open'];
    }

    $scope.prepareToDelete = function (ticket) {
      $scope.ticketToDelete = ticket;
      $scope.ticketToDeleteIndex = $scope.vm.items.indexOf(ticket);
    }

    $scope.deleteTicket = function(ticket) {
      $http({
         data : ticket,
         method : 'POST',
         headers : {
           'Content-Type' : 'application/json'
         },
         url : csContainer.jzURL('TicketAdministrationController.deleteTicket')
     }).then(function successCallback(data) {
         $timeout(function() {
              $scope.setResultMessage("", "info")
         }, 3000);
         //remove the ticket from the array of tickets
         $scope.vm.items.splice($scope.ticketToDeleteIndex,1);
         $scope.tickets.splice($scope.tickets.indexOf(ticket),1);
     },function errorCallback(data) {
         $scope.setResultMessage(data, "error");
     });
    }


    $scope.loadStatuses();
    $scope.loadTickets($scope.selectedFilter);
    $scope.vm.setPage(1);
    $scope.loadBundles();
    $scope.loadAssignees();

    $('#csAddon').css('visibility', 'visible');
    $(".csLoadingBar").remove();
  };
  return csCtrl;
});
