(function() {
  /**
   * Page to view the members of a team and add/remove them.
   */
  angular.module('quayPages').config(['pages', function(pages) {
    pages.create('team-view', 'team-view.html', TeamViewCtrl, {
      'newLayout': true,
      'title': 'Team {{ teamname }}',
      'description': 'Team {{ teamname }}'
    })
  }]);

  function TeamViewCtrl($rootScope, $scope, $timeout, Features, Restangular, ApiService, $routeParams) {
    var teamname = $routeParams.teamname;
    var orgname = $routeParams.orgname;

    $scope.orgname = orgname;
    $scope.teamname = teamname;
    $scope.addingMember = false;
    $scope.memberMap = null;
    $scope.allowEmail = Features.MAILING;

    $rootScope.title = 'Loading...';

    $scope.filterFunction = function(invited, robots) {
      return function(item) {
        // Note: The !! is needed because is_robot will be undefined for invites.
        var robot_check = (!!item.is_robot == robots);
        return robot_check && item.invited == invited;
      };
    };

    $scope.inviteEmail = function(email) {
      if (!email || $scope.memberMap[email]) { return; }

      $scope.addingMember = true;

      var params = {
        'orgname': orgname,
        'teamname': teamname,
        'email': email
      };

      var errorHandler = ApiService.errorDisplay('Cannot invite team member', function() {
        $scope.addingMember = false;
      });

      ApiService.inviteTeamMemberEmail(null, params).then(function(resp) {
        $scope.members.push(resp);
        $scope.memberMap[resp.email] = resp;
        $scope.addingMember = false;
      }, errorHandler);
    };

    $scope.addNewMember = function(member) {
      if (!member || $scope.memberMap[member.name]) { return; }

      var params = {
        'orgname': orgname,
        'teamname': teamname,
        'membername': member.name
      };

      var errorHandler = ApiService.errorDisplay('Cannot add team member', function() {
        $scope.addingMember = false;
      });

      $scope.addingMember = true;
      ApiService.updateOrganizationTeamMember(null, params).then(function(resp) {
        $scope.members.push(resp);
        $scope.memberMap[resp.name] = resp;
        $scope.addingMember = false;
      }, errorHandler);
    };

    $scope.revokeInvite = function(inviteInfo) {
      if (inviteInfo.kind == 'invite') {
        // E-mail invite.
        $scope.revokeEmailInvite(inviteInfo.email);
      } else {
        // User invite.
        $scope.removeMember(inviteInfo.name);
      }
    };

    $scope.revokeEmailInvite = function(email) {
      var params = {
        'orgname': orgname,
        'teamname': teamname,
        'email': email
      };

      ApiService.deleteTeamMemberEmailInvite(null, params).then(function(resp) {
        if (!$scope.memberMap[email]) { return; }
        var index = $.inArray($scope.memberMap[email], $scope.members);
        $scope.members.splice(index, 1);
        delete $scope.memberMap[email];
      }, ApiService.errorDisplay('Cannot revoke team invite'));
    };

    $scope.removeMember = function(username) {
      var params = {
        'orgname': orgname,
        'teamname': teamname,
        'membername': username
      };

      ApiService.deleteOrganizationTeamMember(null, params).then(function(resp) {
        if (!$scope.memberMap[username]) { return; }
        var index = $.inArray($scope.memberMap[username], $scope.members);
        $scope.members.splice(index, 1);
        delete $scope.memberMap[username];
      }, ApiService.errorDisplay('Cannot remove team member'));
    };

    $scope.updateForDescription = function(content) {
      $scope.organization.teams[teamname].description = content;

      var params = {
        'orgname': orgname,
        'teamname': teamname
      };

      var teaminfo = $scope.organization.teams[teamname];
      ApiService.updateOrganizationTeam(teaminfo, params).then(function(resp) {
      }, function() {
        $('#cannotChangeTeamModal').modal({});
      });
    };

    var loadOrganization = function() {
      $scope.orgResource = ApiService.getOrganizationAsResource({'orgname': orgname}).get(function(org) {
        $scope.organization = org;
        $scope.team = $scope.organization.teams[teamname];
        $rootScope.title = teamname + ' (' + $scope.orgname + ')';
        $rootScope.description = 'Team management page for team ' + teamname + ' under organization ' + $scope.orgname;
        loadMembers();
        return org;
      });
    };

    var loadMembers = function() {
      var params = {
        'orgname': orgname,
        'teamname': teamname,
        'includePending': true
      };

      $scope.membersResource = ApiService.getOrganizationTeamMembersAsResource(params).get(function(resp) {
        $scope.members = resp.members;
        $scope.canEditMembers = resp.can_edit;

        $('.info-icon').popover({
          'trigger': 'hover',
          'html': true
        });

        $scope.memberMap = {};
        for (var i = 0; i < $scope.members.length; ++i) {
          var current = $scope.members[i];
          $scope.memberMap[current.name || current.email] = current;
        }

        return resp.members;
      });
    };

    // Load the organization.
    loadOrganization();
  }
})();