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

    $scope.orderByField = 'updateDate';
    $scope.reverseSort = false;
    $scope.spaces = [];
    $scope.currentPage = 0;
    $scope.pageSize = 20
    $scope.def = '';
    $scope.itemsPerPageSugg = [5, 10, 20, 50, 100];
    $scope.vm = this;
    $scope.vm.pager = {};
    $scope.vm.setPage = setPage;

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

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

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

    $scope.typeNames = ["JVMType", "OSType", "ASType", "DBType", "EnvType", "SSOType"];

    $scope.loadBundles = function() {
      $http({
        method : 'GET',
        url : csContainer.jzURL('SettingsController.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.openTab = function (tabName, tabHide) {
                    $("#" + tabName).css("display", "block");
                    $("#" + tabHide).css("display", "none");
                    $("#" + tabName + "Tab").addClass("active");
                    $("#" + tabHide + "Tab").removeClass("active");
                }

    // 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.refreshController = function() {
      try {
        $scope.$digest()
      } catch (excep) {
        // No need to display errors in console
      }
    };

    $scope.loadTypes = function() {
      $http({
        method : 'GET',
        url : csContainer.jzURL('SettingsController.getTypes')
      }).then(function successCallback(data) {
        $scope.types = data.data;
        deferred.resolve(data);
      }, function errorCallback(data) {
        $scope.setResultMessage(data, "error");
      });
    }

       $scope.loadAllEnvironments = function() {
       if($scope.spaces.length == 0 )
           {
                     $http({
                       method : 'GET',
                       url : csContainer.jzURL('SettingsController.loadAllEnvironments')
                     }).then(function successCallback(data) {
                       $scope.spaces = data.data;
                       $scope.vm.setPage(1);
                       deferred.resolve(data);
                     }, function errorCallback(data) {
                       $scope.setResultMessage(data, "error");
                     });
           }
        }


    $scope.saveType = function(newType, typeData) {
      newType.label = typeData.label;
      $http({
        data : newType,
        method : 'POST',
        headers : {
          'Content-Type' : 'application/json'
        },
        url : csContainer.jzURL('SettingsController.saveType')
      }).then(function successCallback(data) {
        $scope.setResultMessage($scope.i18n.typeSaved, "success");
        newType.id = data.data.id;

        $timeout(function() {
          $scope.setResultMessage("", "info")
        }, 3000);
      }, function errorCallback(data) {
        $scope.setResultMessage($scope.i18n.error, "error");
      });
    };

    $scope.editType = function(rowForm) {
      console.log(rowForm);
    };

    $scope.removeType = function(typeName, index) {
      type = $scope.types[typeName][index];
      if(type && type.id) {
        $http({
          data : type,
          method : 'POST',
          headers : {
            'Content-Type' : 'application/json'
          },
          url : csContainer.jzURL('SettingsController.deleteType')
        }).then(function successCallback(data) {
          $scope.setResultMessage($scope.i18n.typeDeleted, "success");
          type = $scope.types[typeName].splice(index, 1);

          $timeout(function() {
            $scope.setResultMessage("", "info")
          }, 3000);
        }, function errorCallback(data) {
          $scope.setResultMessage($scope.i18n.typeDeleteError, "error");
        });
      }
    };

    $scope.addType = function(typeName) {
      $scope.inserted = {
        id: 0,
        label: '',
        type: typeName
      };
      $scope.types[typeName].push($scope.inserted);
    };

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