define("ticketAdminControllers", [ "SHARED/jquery", "SHARED/juzu-ajax"], function($) {
  var csCtrl = function($scope, $q, $timeout, $http, $filter, $window, PagerService) {
    var csContainer = $('#csAddon');
    var deferred = $q.defer();
    var page_location = eXo.env.portal.selectedNodeUri;
    $scope.urlFiltred = true;
	$scope.selectedFilter='myopentickets';
	$scope.ratedTickets=false;

	
    var selectedFilter =  $window.localStorage.getItem("selectedFilter_"+page_location);
    if(selectedFilter!=null){
     $scope.selectedFilter= selectedFilter;
    };
	
    $scope.$watch('selectedFilter', function() {
    if(!$scope.urlFiltred){
		$window.localStorage.setItem("selectedFilter_"+page_location, $scope.selectedFilter);
	}
    });

    $scope.selectedStatusFilter = '';
	
    var selectedStatusFilter =  $window.localStorage.getItem("selectedStatusFilter_"+page_location);
    if(selectedStatusFilter!=null){
     $scope.selectedStatusFilter= selectedStatusFilter;
    };
	
    $scope.$watch('selectedStatusFilter', function() {
     if(!$scope.urlFiltred) {
		 $window.localStorage.setItem("selectedStatusFilter_"+page_location, $scope.selectedStatusFilter);
	 }
    });

    $scope.selectedSpace={groupId:''};
	
    var selectedSpace =  JSON.parse($window.localStorage.getItem("selectedSpace_"+page_location));
    if(selectedSpace!=null){
     $scope.selectedSpace= selectedSpace;
    };

    $scope.$watch('selectedSpace', function() {
      if(!$scope.urlFiltred){
		  $window.localStorage.setItem("selectedSpace_"+page_location, JSON.stringify($scope.selectedSpace));
	  }
    });

    $scope.fileName= "CS_Tickets_Report";
    $scope.tickets = [];
    $scope.filtredTickets = [];
    $scope.assignees = [];
    $scope.severities = [];
    $scope.statuses = [];
    $scope.ticketTypes = [];
    $scope.ownersList = [];
    $scope.currentPage = 0;
    $scope.pageSize = 20
    $scope.def = "";
    $scope.itemsPerPageSugg = [5, 10, 20, 50, 100];
    $scope.allStatusesNames = [];

    $scope.currentSpace='';
    $scope.currentSpaceIncidentFlow = '';
    $scope.currentSpaceInformationFlow = '';
    $scope.ticketToDelete = {};
    $scope.canManage=false;
    $scope.man="_";
    $scope.selectedAssignee=null;
    $scope.selectedOwner=null;
    $scope.selectedSpaceType=null;
    $scope.selectedSeverity=null;
    $scope.selectedAssignee={userName:''};

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

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


   $scope.timeDifference = function(previous) {

    var msPerMinute = 60 * 1000;
    var msPerHour = msPerMinute * 60;
    var msPerDay = msPerHour * 24;
    var msPerMonth = msPerDay * 30;
    var msPerYear = msPerDay * 365;

    var current = new Date();

    var elapsed = current.getTime() - previous;

    if (elapsed < msPerMinute) {
         return Math.round(elapsed/1000) + $scope.i18n.secondsAgo;
    }

    else if (elapsed < msPerHour) {
         return Math.round(elapsed/msPerMinute) +' '+ $scope.i18n.minutesAgo;
    }

    else if (elapsed < msPerDay ) {
         return Math.round(elapsed/msPerHour ) +' '+ $scope.i18n.hoursAgo;
    }

    else if (elapsed < msPerMonth) {
        return Math.round(elapsed/msPerDay) +' '+ $scope.i18n.daysAgo;
    }

    else if (elapsed < msPerYear) {
        return Math.round(elapsed/msPerMonth) +' '+ $scope.i18n.monthsAgo;
    }

    else {
        return Math.round(elapsed/msPerYear ) +' '+ $scope.i18n.yearsAgo;
    }

/*    else {
        return $filter('date')(previous, 'd MMM y');
    }*/
}
             $scope.setReason = function () {
                $scope.ticket.reason="";

                }

    function setPage(page) {
      $scope.filtredTickets = $filter('filter')($scope.tickets, $scope.def);
      if($scope.selectedAssignee!=null && $scope.selectedAssignee.userName!=""){$scope.filtredTickets = $filter('filter')($scope.filtredTickets, {'assignee': $scope.selectedAssignee.userName})};
      if($scope.selectedOwner!=null){$scope.filtredTickets = $filter('filter')($scope.filtredTickets, {'owner': $scope.selectedOwner})};
      if($scope.selectedSpaceType!=null){$scope.filtredTickets = $filter('filter')($scope.filtredTickets, {'internal': $scope.selectedSpaceType})};
      if($scope.selectedSeverity!=null){$scope.filtredTickets = $filter('filter')($scope.filtredTickets, {'severity': $scope.selectedSeverity})};
      if($scope.ratedTickets==true){$scope.filtredTickets = $filter('filter')($scope.filtredTickets, {'customerSatisfied': ''})};
	  $scope.filtredTickets = $filter('orderBy')($scope.filtredTickets, $scope.orderByField, $scope.reverseSort);
	  $scope.resultsLength=$scope.filtredTickets.length;
      // get pager object from service
      $scope.vm.pager = PagerService.GetPager($scope.filtredTickets.length, page, $scope.pageSize);

      // get current page of items
      $scope.vm.items = $scope.filtredTickets.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.setfilter = function() {
    }

   $scope.genarateFileName = function() {
    var d = new Date();
    var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear();
    return "CS_Report_"+datestring;
    }

   $scope.getPaermalink = function() {
     var permalink= window.location.pathname;
     if($scope.selectedSpace.groupId =="" && $scope.selectedAssignee.userName == "" && $scope.selectedOwner == "" && $scope.selectedSpaceType == "" && $scope.selectedStatusFilter == "" && $scope.selectedSeverity == "" && $scope.selectedFilter == ""){
     window.open( permalink, '_blank');
     }else{
     permalink=permalink+"?selectedFilter="+$scope.selectedFilter+"&spaceId="+$scope.selectedSpace.groupId+"&assignee="+$scope.selectedAssignee.userName+"&thirdParty="+$scope.selectedOwner+"&internal="+$scope.selectedSpaceType+"&status="+$scope.selectedStatusFilter+"&severity="+$scope.selectedSeverity ;
     }
     window.open( permalink, '_blank');
    }


    $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() {
      if(!$scope.selectedSpace || $scope.selectedSpace == 'null' || $scope.selectedSpace == 'undefined'){
        $scope.selectedSpace={groupId:''};
      }

       if($scope.currentSpace != ''){
        $scope.selectedSpace={groupId: $scope.currentSpace};
      }

     if(!$scope.selectedStatusFilter || $scope.selectedStatusFilter == 'null' || $scope.selectedStatusFilter == 'undefined'){
        $scope.selectedStatusFilter='';
      }


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

      return deferred.promise;
    };

    $scope.loadSpaces = function() {
      $http({
        method : 'GET',
        url : csContainer.jzURL('TicketAdministrationController.getSpaces')
      }).then(function successCallback(data) {
        $scope.spaces = data.data;
        deferred.resolve(data);
      }, function errorCallback(data) {
        $scope.setResultMessage(data, "error");
      });
    }

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

    $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.getAvatar = function(username){
      for (var i = 0; i < $scope.assignees.length; i++) {
        if ($scope.assignees[i].userName === username) {
           return $scope.assignees[i].avatar;
        }
      }
      return "/eXoSkin/skin/images/system/UserAvtDefault.png";
    }

        $scope.isSupportTeamMember = 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, index) {
    var mybody = angular.element(document).find('body');
            mybody.addClass('waiting');
      $http({
        data : ticket,
        method : 'POST',
        headers : {
         'Content-Type' : 'application/json'
        },
        url : csContainer.jzURL('TicketAdministrationController.saveTicket')
        }).then(function successCallback(data) {
          ticket.id = data.data.id;
          mybody.removeClass('waiting');
          $scope.vm.items[index]= data.data;
        }, function errorCallback(data) {
        mybody.removeClass('waiting');
          $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.getSupportAgents')
       }).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.loadOwnersList = function() {
       $http({
          url : csContainer.jzURL('TicketAdministrationController.getOwnersList')
       }).then(function successCallback(data) {
           $scope.ownersList = data.data;
           $timeout(function() {
                $scope.setResultMessage("", "info")
           }, 3000);
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

    $scope.loadContext = function() {
       $http({
          url : csContainer.jzURL('TicketAdministrationController.getContext')
       }).then(function successCallback(data) {
           $scope.currentSpace = data.data.currentSpace;
           $scope.currentSpaceIncidentFlow = data.data.currentSpaceIncidentFlow;
           $scope.currentSpaceInformationFlow = data.data.currentSpaceInformationFlow;
		   
           $scope.canManage=data.data.canManage;
          var spaceId = $scope.getParameterByName('spaceId');
          var assignee = $scope.getParameterByName('assignee');
          var thirdParty = $scope.getParameterByName('thirdParty');
          var internal = $scope.getParameterByName('internal');
          var status = $scope.getParameterByName('status');
          var severity = $scope.getParameterByName('severity');
          var opvsclStatus = $scope.getParameterByName('opvsclStatus');
          var selectedFilter = $scope.getParameterByName('selectedFilter');
          if(spaceId!=null ||assignee!=null ||thirdParty!=null ||internal!=null ||status!=null|| opvsclStatus!=null|| selectedFilter!=null){
			  $scope.selectedSpace={groupId:""};
			  $scope.selectedAssignee = {userName:""};
			  $scope.selectedOwner = "";
			  $scope.selectedSpaceType = "";
			  $scope.selectedStatusFilter = "";
			  $scope.selectedSeverity = "";
			  
		  }else{
			  $scope.urlFiltred=false;
		  }
          if(spaceId && spaceId.length > 0){
			$scope.selectedSpace={groupId:spaceId};
            $scope.selectedFilter = 'allopentickets';
            
          }

          if(assignee && assignee.length > 0){
            $scope.selectedAssignee = {userName:assignee};
            $scope.selectedFilter = 'allopentickets';
          }
          if(thirdParty && thirdParty.length > 0){
            $scope.selectedOwner = thirdParty;
            $scope.selectedFilter = 'allopentickets';
          }
          if(internal && internal.length > 0){
            $scope.selectedSpaceType = internal;
            $scope.selectedFilter = 'allopentickets';
          }

          if(spaceId && spaceId.length > 0){
            $scope.selectedSpaceType = null;
            $scope.selectedFilter = 'allopentickets';
          }

          if(status && status.length > 0){
            $scope.selectedStatusFilter = status;
            $scope.selectedFilter = 'allopentickets';
          }          

		  if(severity && severity.length > 0){
            $scope.selectedSeverity = severity;
            $scope.selectedFilter = 'allopentickets';
          }
		  
		  if(opvsclStatus && opvsclStatus.length > 0){
            $scope.selectedStatusFilter = opvsclStatus;
            $scope.selectedFilter = 'alltickets';
          }

          if(selectedFilter && selectedFilter.length > 0){
            $scope.selectedFilter = selectedFilter;

          }
		  
           if($scope.canManage){
           $scope.man=""}
           $scope.loadTickets();
           $scope.vm.setPage(1);
		   
           $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;
          for(var key in $scope.statuses){
            if ($scope.statuses.hasOwnProperty(key)){
            if($scope.currentSpace!='' && key!=$scope.currentSpaceIncidentFlow && key!=$scope.currentSpaceInformationFlow) { continue; }
               var statusList = $scope.statuses [key];
               for(var i =0;i < statusList.length; i++){
                 if($scope.allStatusesNames.indexOf(statusList[i].state) == -1){
                   $scope.allStatusesNames.push(statusList[i].state);
                   }
               }
            }
          }
          $timeout(function() {
               $scope.setResultMessage("", "info")
          }, 3000);
      },function errorCallback(data) {
          $scope.setResultMessage(data, "error");
      });
    }

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

    $scope.prepareToDelete = function (ticket) {
     if (!confirm($scope.i18n.confirmDeleteTicket +" "+  ticket.title)) {
                    return;
                }
      $scope.ticketToDelete = ticket;
      $scope.ticketToDeleteIndex = $scope.vm.items.indexOf(ticket);
      $scope.deleteTicket(ticket);
    }

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

    $scope.createTicket = function() {
    var locationHref = window.location.href;
    var indexOfSemiColon = locationHref.lastIndexOf(":spaces:");
    var indexOfSlash = locationHref.indexOf("/", indexOfSemiColon+1);
    if(indexOfSlash <0) indexOfSlash =  locationHref.length
    var spacePrettyName = eXo.env.portal.selectedNodeUri;
    var indexSlashPrettyName = spacePrettyName.indexOf('/');
    if(indexSlashPrettyName > 0) {
    	spacePrettyName = spacePrettyName.substring(0, indexSlashPrettyName);
    }
    var ticketLink = locationHref.substring(0, indexOfSlash) + "/" + spacePrettyName + "/ticket";
    window.location.href = ticketLink;
    }

        $scope.getParameterByName = function (name) {

          var   url = window.location.href;

           name = name.replace(/[\[\]]/g, "\\$&");
           var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
               results = regex.exec(url);
           if (!results) return null;
           if (!results[2]) return '';
           return decodeURIComponent(results[2].replace(/\+/g, " "));
        }



    $scope.loadContext();
    $scope.loadSpaces();
    $scope.loadStatuses();
    $scope.loadBundles();
	$scope.loadAssignees();
    $scope.loadOwnersList();

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