define(function (require) {
  'use strict';

  var states = require('states');
  var modules = require('modules');
  var _ = require('lodash');
  var alienUtils = require('scripts/utils/alien_utils');

  require('scripts/_ref/applications/controllers/applications_detail_environment_deploynext');
  require('scripts/_ref/applications/controllers/applications_detail_environment_deploycurrent');
  require('scripts/_ref/applications/controllers/applications_detail_environment_history');
  require('scripts/common/services/user_context_services');

  states.state('applications.detail.environment', {
    url: '/environment/:environmentId',
    templateUrl: 'views/_ref/applications/applications_detail_environment.html',
    controller: 'ApplicationEnvironmentCtrl',
    resolve: {
      environment: ['applicationEnvironmentsManager', '$stateParams', 'userContextServices',
        function (applicationEnvironmentsManager, $stateParams, userContextServices) {
          return _.catch(function () {
            var environment = applicationEnvironmentsManager.get($stateParams.environmentId);
            userContextServices.setEnvironmentId(environment.applicationId, $stateParams.environmentId);
            return environment;
          });
        }
      ]
    }
  });

  // TODO Manually forward to the state with visibility (users should go to summary)
  states.forward('applications.detail.environment', 'applications.detail.environment.history');

  modules.get('a4c-applications').controller('ApplicationEnvironmentCtrl',
    ['$scope', '$state', 'userContextServices', 'application', 'environment', 'menu', 'applicationEnvironmentsManager', 'breadcrumbsService', '$timeout', 'featureService',
      function ($scope, $state, userContextServices, applicationResponse, environment, menu, applicationEnvironmentsManager, breadcrumbsService,  $timeout, featureService) {
        $scope.application = applicationResponse.data;
        $scope.environment = environment;
        $scope.statusIconCss = alienUtils.getStatusIconCss;
        $scope.statusTextCss = alienUtils.getStatusTextCss;
        $scope.menu = menu;

        featureService.lockNextDeploymentTabs().then(function(data){
          $scope.lockNextDeploymentTabs=data;
        });

        breadcrumbsService.putConfig({
          state: 'applications.detail.environment',
          text: function () {
            return $scope.environment.name;
          },
          onClick: function () {
            $state.go('applications.detail.environment', {
              id: $scope.application.id,
              environmentId: $scope.environment.id
            });
          }
        });

        applicationEnvironmentsManager.onEnvironmentStateChangedCallback = function(env) {
            if ($scope.environment.id === env.id) {
                $scope.setEnvironment(env);
                $scope.$digest();
            }
        };

        function updateMenu() {
          // update menu entry
          var deploycurrent = _.find($scope.menu, { 'state': 'applications.detail.environment.deploycurrent' });
          deploycurrent.disabled = $scope.isState('UNDEPLOYED');
          if (!$scope.isState('UNDEPLOYED') && $scope.lockNextDeploymentTabs == true) {
            // to avoid long processing blocking request on prepare next deployement
            // when the environnement is not undeployed, let's directly go to the active deployment page
            states.forward('applications.detail.environment', 'applications.detail.environment.deploycurrent');
          }
          var deploynext = _.find($scope.menu, { 'state': 'applications.detail.environment.deploynext' });
          if (_.indexOf(['DEPLOYMENT_IN_PROGRESS', 'UNDEPLOYMENT_IN_PROGRESS', 'UPDATE_IN_PROGRESS'], $scope.environment.status) !== -1
            && $scope.lockNextDeploymentTabs == true) {
            deploynext.disabled = true;
          } else {
            deploynext.disabled = false;
          }
        }

        $scope.isState = function (stateName) {
          return $scope.environment.status === stateName;
        };

        $scope.isAnyState = function (stateNames) {
          return _.indexOf(stateNames, $scope.environment.status) !== -1;
        };

        $scope.setState = function(state){
          $scope.environment.status = state;
          updateMenu();
        };

        $scope.setEnvironment = function (env) {
          $scope.environment = env;
          updateMenu();
        };

        $scope.reloadEnvironment = function() {
          applicationEnvironmentsManager.reload($scope.environment.id, function(environment) {
            $scope.setEnvironment(environment);
          });
        };

        $scope.goToApplication = function ($event) {
          $event.preventDefault();
          $event.stopPropagation();
          userContextServices.clear($scope.application.id);
          $state.go('applications.detail', { id: $scope.application.id });
        };

        $scope.onItemClick = function ($event, menuItem) {
          $event.preventDefault();
          $event.stopPropagation();
          if (!menuItem.disabled) {
            $timeout(function() {
              $state.go(menuItem.state);
            }, 100);
          }
        };

        $scope.$watch('environment', function (env) {
          $scope.setEnvironment(env);
          $scope.$emit('$contextPush',
              { type: "Environment",
                data: { environmentId: $scope.environment.id }
              });
        });

        // update variables related to env status
        $scope.setEnvironment($scope.environment);

        if (!$scope.isState('UNDEPLOYED') && $scope.lockNextDeploymentTabs == true) {
          // to avoid long processing blocking request on prepare next deployement
          // when the environnement is not undeployed, let's directly go to the active deployment page
          states.forward('applications.detail.environment', 'applications.detail.environment.deploycurrent');
        }

        $scope.$on('$destroy', function() {
          $scope.$emit('$contextPoll');
        });

      }
    ]);
});
