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.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.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);
                /*$scope.setResultMessage(data, "success");*/
                $scope.showAlert = false;
            }, 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.getAllowedStates();
                deferred.resolve(data);
                /*$scope.setResultMessage(data, "success");*/
                $scope.showAlert = false;
            }, 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;
                        deferred.resolve(data);
                        /*$scope.setResultMessage(data, "success");*/
                        $scope.showAlert = false;
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
         }

    $scope.saveTicket = function(ticket) {
      $http({
        data : ticket,
        method : 'POST',
        headers : {
         'Content-Type' : 'application/json'
        },
        url : ticketMenuContainer.jzURL('TicketMenuController.saveTicket')
        }).then(function successCallback(data) {
        }, function errorCallback(data) {
          $scope.setResultMessage($scope.i18n.ticketSubmitionError, "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.backTickets = 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 ticketsLink = locationHref.substring(0, indexOfSlash) + "/" + spacePrettyName + "/tickets-list";
    window.location.href = ticketsLink;
    }


    $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]) == -1) {
                           allowedSuccessors.splice(j, 1);
                        }
            }
			if(allowedSuccessors.length>0) {
			$scope.showStatuses=true;}
			else{
				$scope.showStatuses=false;
			}
            return allowedSuccessors;
          }
        }
        return [];
    }

	
	$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.getFlowStats();
        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.setResultMessage(data, "error");
      });
        }


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

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

    };
        return ticketMenuCtrl;

});