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

    $scope.typeNames = ["JVMType", "OSType", "ASType", "DBType", "EnvType", "SSOType"];
    $scope.environments = [];
    $scope.showForm = (window.location.href.indexOf("?new=true") > 0 || window.location.href.indexOf("&new=true") > 0);
    $scope.validateForm = false;
    $scope.validateForm = false;
    $scope.returnLink = "";

    $scope.initForm = function(environment) {
      if(environment) {
        $scope.newEnvironment = environment;

        // FIXME Workaround: Select Input Option is not set in edit form whe value is a number

        environment.typeId = '' + environment.typeId;
        environment.asId = '' + environment.asId;
        environment.osId = '' + environment.osId;
        environment.ssoId = '' + environment.ssoId;
        environment.dbId = '' + environment.dbId;
        environment.jvmVendorId = '' + environment.jvmVendorId;
      } else {
        $scope.newEnvironment = {};
      }
    }
    $scope.initForm();

    $scope.getEnvironmentIndexById = function(id){
       for(var i = 0; i < $scope.environments.length; i += 1) {
          if($scope.environments[i].id == id) {
            return i;
          }
        }
       return -1;
    }

    $scope.loadBundles = function() {
      $http({
        method : 'GET',
        url : csContainer.jzURL('EnvironmentController.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.loadEnvironments = function() {
      $http({
        method : 'GET',
        url : csContainer.jzURL('EnvironmentController.getEnvironments')
      }).then(function successCallback(data) {
        $scope.setResultMessage(data, "success");
        $scope.environments = data.data;
        editEnvironmentId = window.location.href.indexOf("?editEnv=") > 0 ? window.location.href.match(/editEnv=[0-9]+/g)[0].replace("editEnv=",""): -1;
        if (editEnvironmentId > -1){
            index = $scope.getEnvironmentIndexById(editEnvironmentId);
            if(index > -1) {
              $scope.editEnvironment($scope.environments[index]);
            }
        }
        $timeout(function() {
          $scope.setResultMessage("", "info")
        }, 3000);
      }, function errorCallback(data) {
        $scope.setResultMessage(data, "error");
      });
    };

    $scope.saveEnvironment = function() {
      $scope.validateForm = true;
      var validationMessage = $scope.validateEnvironmentForm();
      if (validationMessage) {
        $scope.setResultMessage(validationMessage, "warning");
        return;
      }
      $scope.validateForm = false;

      $scope.setResultMessage($scope.i18n.savingEnvironment, "info");
      $http({
        data : $scope.newEnvironment,
        method : 'POST',
        headers : {
          'Content-Type' : 'application/json'
        },
        url : csContainer.jzURL('EnvironmentController.saveEnvironment')
      }).then(function successCallback(data) {
        $scope.initURL = $scope.getParameterByName('initURL');
        if($scope.initURL && $scope.initURL.length > 0){
           var ticketType = $scope.getParameterByName('ticketType');
           var ticketSeverity = $scope.getParameterByName('severity');
           $scope.returnLink = $scope.initURL+"?ticketType="+ticketType+"&severity="+ticketSeverity;
        }
        $scope.setResultMessage($scope.i18n.environmentSaved, "success");
        $scope.environments = data.data;
        $scope.initForm();
        $scope.showForm = false;
      }, function errorCallback(data) {
        $scope.setResultMessage($scope.i18n.environmentSaveError, "error");
      });
      $window.scrollTo(0, 0);
    }

    $scope.editEnvironment = function(environment) {
      $scope.initForm(environment);
      $scope.showForm = true;
    };

    $scope.deleteEnvironment = function(environment) {
      if (!confirm($scope.i18n.deleteEnvironmentConfirm + "'" + environment.name + "' ?")) {
        return;
      }
      $scope.setResultMessage($scope.i18n.deletingEnvironment, "info");
      $http({
        data : environment,
        method : 'POST',
        headers : {
          'Content-Type' : 'application/json'
        },
        url : csContainer.jzURL('EnvironmentController.deleteEnvironment')
      }).then(function successCallback(data) {
        $scope.setResultMessage($scope.i18n.environmentDeleted, "success");
        $scope.environments = data.data;
        $scope.showForm = false;

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

    // 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.validateEnvironmentForm = function(environment) {
      return null;
    };

    $scope.refreshController = function() {
      try {
        $scope.$digest()
      } catch (excep) {
        // No need to display errors in console
      }
    };

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

    $scope.isOldEnv = function(environment) {
      return Math.floor((new Date() - environment.updateDate) / (1000 * 3600 * 24)) > 90
    };

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

        $timeout(function() {
          $scope.setResultMessage("", "info")
        }, 3000);
      }, function errorCallback(data) {
        $scope.setResultMessage($scope.i18n.saveError, "error");
      });
    };
    /************* *///////////////////////
    $scope.getParameterByName = function (name, url) {
     if (!url) {
       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.loadEnvironments();
    $scope.loadBundles();
    $scope.loadTypes();
    $('#csAddon').css('visibility', 'visible');
    $(".csLoadingBar").remove();
  };
  return csCtrl;
});