define("ticketMenuControllers", ["SHARED/jquery", "SHARED/juzu-ajax"], function ($, jz) {
    var ticketMenuCtrl = function ($scope, $q, $timeout, $http, $filter) {
        var ticketMenuContainer = $('#ticketMenu');
        var deferred = $q.defer();

        $scope.ticket=null;
        $scope.flowStatuses=[];
        $scope.allowedStates=[];
		$scope.showStatuses=false;
		$scope.showEdit=false;
		$scope.assignees=[];
		$scope.ownersList=[];
		$scope.ticketTypes=[];
		$scope.severities=[];
		$scope.currentUser = "";
        $scope.canManage= false;
        $scope.disabled= false;
        $scope.showReason= true;
        $scope.ticket_= {};
        $scope.status_=null;
        $scope.reasons=[];
        $scope.allStatusesNames=[];
        $scope.successors=[];
        $scope.man="_";
        $scope.showEnv= false;
        $scope.editReason= false;
        $scope.editSelectReason = false;


$scope.editSelect = function () {
 $scope.editSelectReason = true;
}

$scope.hideEditReason = function () {
$scope.editReason= false;
 $scope.editSelectReason = false;
}
$scope.showEditReason = function () {
/* $scope.reasons=$scope.ticket.status.reason; */
$scope.editReason= true;
 $scope.editSelectReason = false;
}
        $scope.setResultMessage = function (text, type) {
            $scope.resultMessageClass = "alert-" + type;
            $scope.resultMessageClassExt = "uiIcon" + type.charAt(0).toUpperCase()+ type.slice(1);
            $scope.showAlert = true;
            $scope.resultMessage = text;
        }

             $scope.saveStatus = function (status) {
                        $scope.ticket.status=status.state;
                        $scope.reasons=status.reason;
                        if($scope.reasons.length>=1){
                          $scope.ticket.reason=$scope.reasons[0];
                        }
                        $scope.saveTicket();
                        $scope.getAllowedStates();
                }


             $scope.setReason = function () {
                $scope.ticket.reason="";
                var succ = $scope.getAllStatusSuccessors($scope.status_)
                   for (var i = 0; i < succ.length; i++) {
                     if (succ[i].state === $scope.ticket.status) {
                        $scope.ticket.reason=succ[i].reason[0];
                     }
                   }
                }



        $scope.hideStatusReason = function () {
			 $scope.editSelectReason = false;
                $scope.ticket_.status=$scope.ticket_.status;
                $scope.ticket_.reason=$scope.reasons[0];
                $scope.showReason= true;
        }

        $scope.toggleEnv = function () {
                $scope.showEnv=!$scope.showEnv;
        }

        $scope.saveReason = function () {
                $scope.showReason= false;
                $scope.editReason= false;
				 $scope.editSelectReason = false;
                $scope.saveTicket();
       }


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


        $scope.getEnvironment = function () {
            $http({
                method: 'GET',
                url: ticketMenuContainer.jzURL('TicketMenuController.getEnvironment') + "&id=" + $scope.ticket.environmentId
            }).then(function successCallback(data) {
                $scope.enveronment = data.data;
                deferred.resolve(data);
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }


        $scope.getFlowStats = function () {
            $http({
                method: 'GET',
                url: ticketMenuContainer.jzURL('TicketMenuController.getFlowStats') + "&name=" + $scope.ticket.flow
            }).then(function successCallback(data) {
                $scope.flowStatuses = data.data;
				$scope.allStatusesNames = [];
				for(var i =0;i < $scope.flowStatuses.length; i++){
                   $scope.allStatusesNames.push($scope.flowStatuses[i]);
                   if($scope.flowStatuses[i].state==$scope.ticket.status){
                   $scope.reasons=$scope.flowStatuses[i].reason;
                   }

               }
                $scope.getAllowedStates();
                deferred.resolve(data);
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }


         $scope.getAllowedStates = function () {
             $http({
                        method: 'GET',
                        url: ticketMenuContainer.jzURL('TicketMenuController.getAllowedStates') + "&name=" + $scope.ticket.flow
                    }).then(function successCallback(data) {
                        $scope.allowedStates = data.data;
						$scope.getStatusSuccessors($scope.ticket.status);
                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
         }

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


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


    $scope.editTicket = function() {
        $scope.status_=$scope.ticket.status;
		if($scope.severities.length==0)$scope.loadSeverities();
		if($scope.assignees.length==0)$scope.loadAssignees();
        if($scope.ticketTypes.length==0)$scope.loadTicketTypes();
        if($scope.ownersList.length==0)$scope.loadOwnersList();
    }


    $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.backTickets = function() {
        var  adminLink="";
        var locationHref = window.location.href;
        var prevLocationHref = document.referrer;
        var indexOfSemiColon = locationHref.lastIndexOf(":spaces:");
        var indexOfPrevSemiColon = prevLocationHref.lastIndexOf(":spaces:");
        if(prevLocationHref.endsWith('csticketmgmt')){
            adminLink = "/portal/g/:platform:administrators/csmgmt/csticketmgmt"
        }
        else if(prevLocationHref.endsWith('cssupporttickets')){
            adminLink = "/portal/g/:support-team/cssupporttickets";
        }

        else	{
            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);
            }
            adminLink = locationHref.substring(0, indexOfSlash) + "/" + spacePrettyName + "/tickets-list";

        }
        window.location.href = adminLink;
    }


    $scope.getStatusSuccessors = function(status) {

        if(!status){
           status = 'open';
        }
		if ($scope.allowedStates.length==0) return [];
        for (var i=0 ; i < $scope.flowStatuses.length ; i++){
          if($scope.flowStatuses[i].state === status){

            var allowedSuccessors = $scope.flowStatuses[i].successors;
            for(var j = allowedSuccessors.length - 1; j >= 0; j--) {
                    if($scope.allowedStates.indexOf(allowedSuccessors[j].state) == -1) {
                           allowedSuccessors.splice(j, 1);
                        }
            }
			if(allowedSuccessors.length>0) {
			$scope.showStatuses=true;}
			else{
				$scope.showStatuses=false;
			}
            $scope.successors= allowedSuccessors;
          }
        }
        return [];
    }

    $scope.getAllStatusSuccessors = function(status) {

        if(!status){
           status = 'open';
        }
		if ($scope.allowedStates.length==0) return [];
        for (var i=0 ; i < $scope.flowStatuses.length ; i++){
          if($scope.flowStatuses[i].state === status){

            return allowedSuccessors = $scope.flowStatuses[i].successors;


          }
        }
        return [];
    }

    $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 "empty";
    }


	$scope.getTicket = function() {
      $http({
        method : 'GET',
        url : ticketMenuContainer.jzURL('TicketMenuController.getTicket')
      }).then(function successCallback(data) {
        $scope.ticket = data.data;
       if($scope.ticket.attachedJira!=null) $scope.getJiraDetails($scope.ticket.attachedJira);
       $scope.disabledVote = ($scope.ticket.assignee == $scope.currentUser);
       if(!$scope.ticket.active){
       $scope.setResultMessage($scope.i18n.subscriptionExpiredMsg, "warning");
       }
        $scope.getFlowStats();
        if($scope.ticket.environmentId!=null) $scope.getEnvironment();

        deferred.resolve(data);
      }, function errorCallback(data) {
        $scope.setResultMessage(data, "error");
      });
    }



        $scope.getJiraDetails = function (id) {
      $http({
        method : 'GET',
        url : ticketMenuContainer.jzURL('TicketMenuController.getJiraDetails') + "&id=" + id
      }).then(function successCallback(data) {
        $scope.ticket.jiraStatus = data.data.fields.status.id;
		$scope.ticket.jiraStatusIcon = data.data.fields.status.iconUrl;
      }, function errorCallback(data) {

      });
        }



    $scope.loadAssignees = function() {
       $http({
          method : 'GET',
          headers : {
            'Content-Type' : 'application/json'
          },
          url : ticketMenuContainer.jzURL('TicketMenuController.getSupportUsernames')
       }).then(function successCallback(data) {
           $scope.assignees = data.data;
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

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

    $scope.loadTicketTypes = function() {
       $http({
          url : ticketMenuContainer.jzURL('TicketMenuController.getTicketTypes')
       }).then(function successCallback(data) {
           $scope.ticketTypes = data.data;
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

    $scope.loadOwnersList = function() {
       $http({
          url : ticketMenuContainer.jzURL('TicketMenuController.getOwnersList')
       }).then(function successCallback(data) {
           $scope.ownersList = data.data;
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }

    $scope.loadContext = function() {
       $http({
          url : ticketMenuContainer.jzURL('TicketMenuController.getContext')
       }).then(function successCallback(data) {
           $scope.currentUser = data.data.currentUser;
           $scope.canManage=data.data.canManage;
           if($scope.canManage){ $scope.man=""}
       },function errorCallback(data) {
           $scope.setResultMessage(data, "error");
       });
    }



        $scope.loadBundle();
		$scope.loadContext();
		$scope.loadAssignees();

        var locationHref = window.location.href;
        if(locationHref.indexOf("/forum/topic/") >0) {
        $scope.getTicket();
        $('#ticketMenu').css('visibility', 'visible');
        }

        $(".csLoadingBar").remove();

    };
        return ticketMenuCtrl;

});
