public void SetTeam_WithExistingTeam_ShouldUpdateTeam()
        {
            #region Arrange
            // Arrange

            Guid tournamentId;
            Tournament tournament;

            {
                #region Create tournament

                // Create tournament
                tournamentId = Guid.NewGuid();
                tournament = new Tournament
                {
                    Id = tournamentId,
                    TeamSize = 2
                };

                #endregion
            }

            Guid organizationId = Guid.NewGuid();
            TournamentOrganizationRegistration registration;
            {
                #region Create registration

                // Create registration

                registration = new TournamentOrganizationRegistration
                {
                    TournamentId = tournamentId,
                    Tournament = tournament,
                    OrganizationId = organizationId,
                    TeamsWanted = 2,
                    TeamsGranted = 2,
                    TeamsPaid = 2,
                };

                unitOfWork.GetRepository<TournamentOrganizationRegistration>().Insert(registration);
                unitOfWork.Save();

                #endregion

            }

            Team team;
            {
                #region Create original team

                // Create original team

                team = new Team
                {
                    Id = Guid.NewGuid(),
                    TournamentId = tournamentId,
                    Tournament = tournament,
                    OrganizationId = organizationId
                };

                for (int i = 0; i < tournament.TeamSize; i++)
                {
                    var speaker = new User
                    {
                        Id = Guid.NewGuid().ToString()
                    };
                    var task = userManager.CreateAsync(speaker);
                    if (!task.IsCompleted) { task.Wait(); }
                    team.Speaker.Add(speaker);
                }

                unitOfWork.GetRepository<Team>().Insert(team);
                unitOfWork.Save();

                #endregion
            }

            Team updatedTeam;
            {
                #region Create updated team

                // Create updated Team

                updatedTeam = new Team
                {
                    Id = team.Id,
                    TournamentId = team.TournamentId,
                    Tournament = tournament,
                    OrganizationId = team.OrganizationId,
                };

                foreach (var speaker in team.Speaker)
                {
                    updatedTeam.Speaker.Add(speaker);
                }

                {
                    #region Replace first speaker

                    // Replace first speaker

                    User newSpeaker = new User
                    {
                        Id = Guid.NewGuid().ToString()
                    };
                    var task = userManager.CreateAsync(newSpeaker);
                    if (!task.IsCompleted) { task.Wait(); }

                    updatedTeam.Speaker[0] = newSpeaker;

                    #endregion
                }

                #endregion
            }
            User user = new User();

            #endregion

            // Act

            var result = tournamentRegistrationsManager.SetTeam(updatedTeam, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.TeamUpdated, result);
            var teamId = team.Id;
            team = null;
            team = tournamentRegistrationsManager.GetTeam(teamId);
            Assert.AreEqual(updatedTeam.Speaker[0].Id, team.Speaker[0].Id);


        }
        public void RemoveSpeaker_WithInvalidSpeakerId_ShouldReturnUserNotFound()
        {
            // Arrange

            String speakerId = Guid.NewGuid().ToString();

            Guid teamId = Guid.NewGuid();
            Team team = new Team
            {
                Id = teamId
            };
            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();


            User user = new User();

            // Act

            var result = tournamentRegistrationsManager.RemoveSpeaker(teamId, speakerId, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.UserNotFound, result);
        }
        public void SetTeam_WithNewTeam_ShouldCreateNewTeam()
        {
            #region Arrange
            // Arrange

            Guid tournamentId = Guid.NewGuid();
            Tournament tournament = new Tournament
            {
                Id = tournamentId,
                TeamSize = 2
            };

            Guid organizationId = Guid.NewGuid();

            TournamentOrganizationRegistration registration = new TournamentOrganizationRegistration
            {
                TournamentId = tournamentId,
                Tournament = tournament,
                OrganizationId = organizationId,
                TeamsWanted = 2,
                TeamsGranted = 2,
                TeamsPaid = 2,
            };

            unitOfWork.GetRepository<TournamentOrganizationRegistration>().Insert(registration);
            unitOfWork.Save();

            Team team = new Team
            {
                Id = Guid.NewGuid(),
                TournamentId = tournamentId,
                Tournament = tournament,
                OrganizationId = organizationId
            };

            for (int i = 0; i < tournament.TeamSize; i++)
            {
                var speaker = new User
                {
                    Id = Guid.NewGuid().ToString()
                };
                var task = userManager.CreateAsync(speaker);
                if (!task.IsCompleted) { task.Wait(); }
                team.Speaker.Add(speaker);
            }

            User user = new User();

            #endregion
            // Act

            var result = tournamentRegistrationsManager.SetTeam(team, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.TeamAdded, result);
            var teamId = team.Id;
            team = null;
            team = tournamentRegistrationsManager.GetTeam(teamId);
            Assert.AreEqual(teamId, team.Id);

        }
        public void AddSpeakerAsync_WithUserAlreadyInOtherTeam_ShouldReturnUserAlreadyInOtherTeam()
        {
            // Arrange
            String speakerId = Guid.NewGuid().ToString();
            User speaker = new User { Id = speakerId };
            var userTask = userManager.CreateAsync(speaker);
            if (!userTask.IsCompleted) { userTask.Wait(); }

            var tournament = new Tournament
            {
                TeamSize = 2
            };
            var teamId = Guid.NewGuid();

            Team team = new Team
            {
                Id = Guid.NewGuid(),
                Tournament = tournament
            };

            team.Speaker.Add(speaker);
            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();

            team = new Team
            {
                Id = teamId,
                Tournament = tournament
            };

            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();


            User user = new User();

            // Act

            var task = tournamentRegistrationsManager.AddSpeakerAsync(teamId, speakerId, user);
            if (!task.IsCompleted)
            {
                task.Wait();
            }
            var result = task.Result;

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.SpeakerAlreadyInOtherTeam, result);

        }
        public void RemoveSpeaker_WithValidTeamIdAndSpeakerId_ShouldRemoveUser()
        {
            // Arrange

            String speakerId = Guid.NewGuid().ToString();
            User speaker = new User { Id = speakerId };
            var userTask = userManager.CreateAsync(speaker);
            if (!userTask.IsCompleted) { userTask.Wait(); }

            Guid teamId = Guid.NewGuid();
            Team team = new Team
            {
                Id = teamId
            };
            team.Speaker.Add(speaker);
            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();

            User user = new User();

            // Act

            var result = tournamentRegistrationsManager.RemoveSpeaker(teamId, speakerId, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.TeamUpdated, result);
            team = tournamentRegistrationsManager.GetTeam(teamId);
            speaker = team.Speaker.FirstOrDefault(sp => sp.Id == speakerId);
            Assert.IsNull(speaker);
        }
        public void AddSpeakerAsync_ExceedingTeamSize_ShouldReturnTooManySpeakers()
        {
            // Arrange
            var tournament = new Tournament
            {
                TeamSize = 2
            };
            var teamId = Guid.NewGuid();

            Team team = new Team
            {
                Id = teamId,
                Tournament = tournament
            };

            for (int i = 0; i < 2; i++)
            {
                team.Speaker.Add(new User());
            }

            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();

            String speakerId = Guid.NewGuid().ToString();
            User speaker = new User { Id = speakerId };
            var userTask = userManager.CreateAsync(speaker);
            if (!userTask.IsCompleted) { userTask.Wait(); }

            User user = new User();

            // Act

            var task = tournamentRegistrationsManager.AddSpeakerAsync(teamId, speakerId, user);
            if (!task.IsCompleted)
            {
                task.Wait();
            }
            var result = task.Result;

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.TooManySpeakers, result);

        }
        public void AddSpeakerAsync_WithInvalidUserId_ShouldReturnUserNotFound()
        {
            // Arrange
            String speakerId = Guid.NewGuid().ToString();

            var tournament = new Tournament
            {
                TeamSize = 2
            };
            var teamId = Guid.NewGuid();

            Team team = new Team
            {
                Id = teamId,
                Tournament = tournament
            };

            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();


            User user = new User();

            // Act

            var task = tournamentRegistrationsManager.AddSpeakerAsync(teamId, speakerId, user);
            if (!task.IsCompleted)
            {
                task.Wait();
            }
            var result = task.Result;

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.UserNotFound, result);

        }
        public void GetTeam_WithValidTeamId_ShouldReturnTeam()
        {
            // Arrange

            var id = Guid.NewGuid();
            Team team = new Team
            {
                Id = id,
                Name = "Team A"
            };
            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();
            team = null;

            // Act

            team = tournamentRegistrationsManager.GetTeam(id);

            // Assert

            Assert.AreEqual(id, team.Id);

        }
        public void AddSpeakerAsync_WithValidTeamIdAndValidSpeakerId_ShouldAddSpeaker()
        {
            // Arrange

            var tournament = new Tournament
            {
                Id = Guid.NewGuid(),
                TeamSize = 2
            };

            unitOfWork.GetRepository<Tournament>().Insert(tournament);
            unitOfWork.Save();

            Organization organization = new Organization
            {
                Id = Guid.NewGuid()
            };

            unitOfWork.GetRepository<Organization>().Insert(organization);
            unitOfWork.Save();

            var teamId = Guid.NewGuid();


            Team team = new Team
            {
                Id = teamId,
                Tournament = tournament,
                TournamentId = tournament.Id,
                Organization = organization,
                OrganizationId = organization.Id
            };

            unitOfWork.GetRepository<Team>().Insert(team);
            unitOfWork.Save();

            String speakerId = Guid.NewGuid().ToString();
            User speaker = new User { Id = speakerId };
            var userTask = userManager.CreateAsync(speaker);
            if (!userTask.IsCompleted) { userTask.Wait(); }

            User user = new User();

            // Act

            var task = tournamentRegistrationsManager.AddSpeakerAsync(teamId, speakerId, user);
            if (!task.IsCompleted)
            {
                task.Wait();
            }
            var result = task.Result;

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.TeamUpdated, result);
            team = tournamentRegistrationsManager.GetTeam(teamId);
            speaker = team.Speaker.FirstOrDefault(sp => sp.Id == speakerId);
            Assert.IsNotNull(speaker);

        }
        public void GenerateAutoSuffix_For702Teams_ShouldReturnZZAsSuffixForLastTeam()
        {
            // Arrange

            Guid organizationId = Guid.NewGuid();
            Guid tournamentId = Guid.NewGuid();
            String abbreviation = "Org";
            AddRegistrationWithOrganizationToRepository(organizationId, tournamentId, abbreviation);

            // Act

            for (int i = 0; i < 702; i++)
            {
                var autoSuffix = tournamentRegistrationsManager.GenerateAutosuffix(organizationId, tournamentId);
                Team team = new Team
                {
                    Id = Guid.NewGuid(),
                    OrganizationId = organizationId,
                    TournamentId = tournamentId,
                    AutoSuffix = autoSuffix
                };
                unitOfWork.GetRepository<Team>().Insert(team);
                unitOfWork.Save();
            }

            // Assert

            var teams = tournamentRegistrationsManager.GetTeams(tournamentId, organizationId)
                .OrderBy(t => t.AutoSuffix).ToList();
            Assert.AreEqual("A", teams.First().AutoSuffix);
            Assert.AreEqual("ZZ", teams.Last().AutoSuffix);
        }
        public void GetTeams_WithValidTournamentId_ShouldReturnTeams()
        {
            #region Arrange

            // Arrange

            Guid organizationId = Guid.NewGuid();
            Guid tournamentId = Guid.NewGuid();

            #region Team 1

            Team team = new Team
            {
                Id = Guid.NewGuid(),
                TournamentId = tournamentId,
                OrganizationId = organizationId
            };

            unitOfWork.GetRepository<Team>().Insert(team);
            #endregion

            #region Team 2

            team = new Team
            {
                Id = Guid.NewGuid(),
                TournamentId = tournamentId,
                OrganizationId = organizationId
            };
            unitOfWork.GetRepository<Team>().Insert(team);
            #endregion

            #region Deleted Team
            team = new Team
            {
                Id = Guid.NewGuid(),
                TournamentId = tournamentId,
                OrganizationId = organizationId,
                Deleted = true
            };
            unitOfWork.GetRepository<Team>().Insert(team);
            #endregion

            unitOfWork.Save();

            #endregion

            // Act

            var teams = tournamentRegistrationsManager.GetTeams(tournamentId);

            // Assert

            Assert.AreEqual(2, teams.Count());

        }
        public void SetTeam_WithMaximumTeamsExceeded_ShouldReturnTooManyTeams()
        {
            #region Arrange
            // Arrange

            Guid tournamentId;
            Tournament tournament;

            {
                #region Create tournament

                // Create tournament
                tournamentId = Guid.NewGuid();
                tournament = new Tournament
                {
                    Id = tournamentId,
                    TeamSize = 2
                };

                #endregion
            }

            Guid organizationId = Guid.NewGuid();
            TournamentOrganizationRegistration registration;
            {
                #region Create registration

                // Create registration

                registration = new TournamentOrganizationRegistration
                {
                    TournamentId = tournamentId,
                    Tournament = tournament,
                    OrganizationId = organizationId,
                    TeamsWanted = 2,
                    TeamsGranted = 2,
                    TeamsPaid = 2,
                };

                unitOfWork.GetRepository<TournamentOrganizationRegistration>().Insert(registration);
                unitOfWork.Save();

                #endregion

            }

            Team team;

            {
                #region Create maximum number of teams

                // Create maximum number of teams

                for (int i = 0; i < registration.TeamsPaid; i++)
                {
                    team = new Team
                    {
                        Id = Guid.NewGuid(),
                        TournamentId = tournamentId,
                        Tournament = tournament,
                        OrganizationId = organizationId
                    };

                    for (int s = 0; s < tournament.TeamSize; s++)
                    {
                        var speaker = new User
                        {
                            Id = Guid.NewGuid().ToString()
                        };
                        var task = userManager.CreateAsync(speaker);
                        if (!task.IsCompleted) { task.Wait(); }
                        team.Speaker.Add(speaker);
                    }

                    unitOfWork.GetRepository<Team>().Insert(team);
                    unitOfWork.Save();
                }

                #endregion
            }

            {
                #region Create new team

                // Create new Team

                team = new Team
                {
                    Id = Guid.NewGuid(),
                    TournamentId = tournamentId,
                    Tournament = tournament,
                    OrganizationId = organizationId,
                };

                #endregion
            }
            User user = new User();

            #endregion

            // Act

            var result = tournamentRegistrationsManager.SetTeam(team, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.TooManyTeams, result);

        }
        public void SetTeam_WithSpeakerInOutherTeam_ShouldReturnSpeakerAlreadyInOtherTeam()
        {
            #region Arrange
            // Arrange

            Guid tournamentId;
            Tournament tournament;

            {
                #region Create tournament

                // Create tournament
                tournamentId = Guid.NewGuid();
                tournament = new Tournament
                {
                    Id = tournamentId,
                    TeamSize = 2
                };

                #endregion
            }

            Guid organizationId = Guid.NewGuid();
            TournamentOrganizationRegistration registration;
            {
                #region Create registration

                // Create registration

                registration = new TournamentOrganizationRegistration
                {
                    TournamentId = tournamentId,
                    Tournament = tournament,
                    OrganizationId = organizationId,
                    TeamsWanted = 2,
                    TeamsGranted = 2,
                    TeamsPaid = 2,
                };

                unitOfWork.GetRepository<TournamentOrganizationRegistration>().Insert(registration);
                unitOfWork.Save();

                #endregion

            }

            Team team;
            {
                #region Create original team

                // Create original team

                team = new Team
                {
                    Id = Guid.NewGuid(),
                    TournamentId = tournamentId,
                    Tournament = tournament,
                    OrganizationId = organizationId
                };

                for (int i = 0; i < tournament.TeamSize; i++)
                {
                    var speaker = new User
                    {
                        Id = Guid.NewGuid().ToString()
                    };
                    var task = userManager.CreateAsync(speaker);
                    if (!task.IsCompleted) { task.Wait(); }
                    team.Speaker.Add(speaker);
                }

                unitOfWork.GetRepository<Team>().Insert(team);
                unitOfWork.Save();

                #endregion
            }

            Team newTeam;
            {
                #region Create new team

                // Create new Team

                newTeam = new Team
                {
                    Id = Guid.NewGuid(),
                    TournamentId = team.TournamentId,
                    Tournament = tournament,
                    OrganizationId = team.OrganizationId,
                };

                // Add new speaker as first speaker

                User newSpeaker = new User { Id = Guid.NewGuid().ToString() };
                var task = userManager.CreateAsync(newSpeaker);
                if (!task.IsCompleted) { task.Wait(); }
                newTeam.Speaker.Add(newSpeaker);

                // Add speaker of another team as second speaker

                newTeam.Speaker.Add(team.Speaker.First());

                #endregion
            }
            User user = new User();

            #endregion

            // Act

            var result = tournamentRegistrationsManager.SetTeam(newTeam, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.SpeakerAlreadyInOtherTeam, result);

        }
        public void SetTeam_WithoutRegistration_ShouldReturnRegistrationNotFound()
        {
            // Arrange

            Team team = new Team { };
            User user = new User();

            // Act

            var result = tournamentRegistrationsManager.SetTeam(team, user);

            // Assert

            Assert.AreEqual(SetTeamOrAdjudicatorResult.RegistrationNotFound, result);

        }
        // GET: TournamentRegistration/Display
        /// <summary>
        /// Displays the registration of an organization for a tournament.
        /// </summary>
        /// <param name="tournamentId">ID of tournament</param>
        /// <returns>Redirect to login, if the user is not logged in.
        /// Redirect to organization selection, if there is no current organization.
        /// Redirect to Home, if the user is not a delegate of the organization.
        /// View to display registration information.</returns>
        public async Task<ActionResult> Display(Guid tournamentId, Guid? organizationId = null, String tab = "")
        {

            #region Checks
            // Get user

            var ident = HttpContext.User.Identity as ClaimsIdentity;
            var userId = ident.GetUserId();
            var user = await userManager.FindByIdAsync(userId);

            Guid currentOrganizationId = Guid.Empty;

            // Get organizationId parameter

            if (organizationId != null)
            {
                currentOrganizationId = (Guid)organizationId;
            }

            // If we do not have an organizationId parameter, get the organizationId from the user object

            if (currentOrganizationId == Guid.Empty)
            {
                var currentOrganizationIdNullable = user.CurrentOrganizationId;
                currentOrganizationId = (Guid)(currentOrganizationIdNullable == null ? Guid.Empty : currentOrganizationIdNullable);
            }

            // If still do not have an organizationId, let the user select an organization

            if (currentOrganizationId == Guid.Empty)
            {
                String returnUrl = null;

                if (HttpContext != null
                    && HttpContext.Request != null)
                {
                    returnUrl = HttpContext.Request.RawUrl;
                }

                return RedirectToAction("Select", "Organization", new { returnUrl = returnUrl });
            }


            // Check user permissions: Either organization delegate or slot manager for tournament

            if (!userManager.HasOrganizationRole(userId, currentOrganizationId, OrganizationRole.Delegate)
                && !userManager.HasTournamentRole(userId, tournamentId, TournamentRole.SlotManager))
            {
                return RedirectToAction("Index", "Home");
            }

            #endregion
            // Everything okay, get the registration

            var registration = tournamentRegistrationsManager.GetRegistration(tournamentId, currentOrganizationId);

            // If we found a registration, build the view model

            if (registration != null)
            {
                TournamentOrganizationRegistrationViewModel viewModel = new TournamentOrganizationRegistrationViewModel
                {
                    Registration = registration,
                    Bookings = bookingManager.GetBookings(registration.OrganizationId, registration.TournamentId)
                };

                #region Teams

                var teams = tournamentRegistrationsManager
                    .GetTeams(registration.TournamentId, registration.OrganizationId)
                    .OrderBy(t => t.Created)
                    .ToList(); ;
                //viewModel.TeamsCompleted = teams.Count();

                // Generate Autosuffix if necessary

                foreach (Team team in teams)
                {
                    if (String.IsNullOrWhiteSpace(team.AutoSuffix))
                    {
                        team.AutoSuffix = tournamentRegistrationsManager.GenerateAutosuffix(registration.OrganizationId, registration.TournamentId, teams);
                        tournamentRegistrationsManager.SetTeam(team, user);
                    }
                }


                // Add teams to view model

                foreach (var team in teams)
                {
                    viewModel.Teams.Add(new APIModels.Team(team));
                }

                // Calculate completed teams

                viewModel.TeamsCompleted = teams.Where(t => t.Speaker.Count >= t.Tournament.TeamSize).Count();

                // if we do not get as many teams as confirmed, add empty teams

                var missingTeams = registration.TeamsPaid - viewModel.Teams.Count;

                for (int i = 0; i < missingTeams; i++)
                {
                    var team = new Team
                    {
                        Id = Guid.NewGuid(),
                        OrganizationId = registration.OrganizationId,
                        Organization = registration.Organization,
                        TournamentId = registration.TournamentId,
                        Tournament = registration.Tournament,
                        AutoSuffix = tournamentRegistrationsManager.GenerateAutosuffix(currentOrganizationId, tournamentId, teams),
                        Name = tournamentRegistrationsManager.GenerateTeamName(currentOrganizationId, tournamentId, teams)
                    };

                    tournamentRegistrationsManager.SetTeam(team, user);
                    viewModel.Teams.Add(new APIModels.Team(team));

                    teams = tournamentRegistrationsManager
                        .GetTeams(registration.TournamentId, registration.OrganizationId)
                        .OrderBy(t => t.Created)
                        .ToList(); ;
                }



                // add empty speakers to view model, if necessary

                foreach (var team in viewModel.Teams)
                {
                    var missingSpeakers = registration.Tournament.TeamSize - team.speakers.Count;
                    for (int i = 0; i < missingSpeakers; i++)
                    {
                        var speaker = new APIModels.User
                        {
                            firstname = Resources.TournamentRegistration.Display.Strings.DefaultFirstName,
                            lastname = Resources.TournamentRegistration.Display.Strings.DefaultLastName
                        };
                        team.speakers.Add(speaker);
                    }

                }
                #endregion



                #region Adjudicators

                // Adjudicators

                var adjudicators = tournamentRegistrationsManager
                    .GetAdjudicators(registration.TournamentId, registration.OrganizationId)
                    .OrderBy(t => t.Created)
                    .ToList();

                viewModel.AdjudicatorsCompleted = adjudicators.Count();

                // if we do not get as many adjudicators as confirmed, add empty adjudicators to view model


                // Add teams to view model

                foreach (var adjudicator in adjudicators)
                {
                    viewModel.Adjudicators.Add(new APIModels.Adjudicator(adjudicator));
                }

                var missingAdjudicators = registration.AdjudicatorsPaid - viewModel.Adjudicators.Count;

                for (int i = 0; i < missingAdjudicators; i++)
                {
                    viewModel.Adjudicators.Add(new APIModels.Adjudicator
                    {
                        organizationId = organizationId,
                        tournamentId = tournamentId,
                        user = new APIModels.User
                        {
                            firstname = Resources.TournamentRegistration.Display.Strings.DefaultFirstName,
                            lastname = Resources.TournamentRegistration.Display.Strings.DefaultLastName
                        }
                    });
                }



                #endregion
                ViewBag.Tab = tab;
                return View(viewModel);
            }

            // if we did not find the registration, display the organization instead

            return RedirectToAction("Display", "Organization");
        }
        public SetTeamOrAdjudicatorResult SetTeam(Team team, User user)
        {

            var registration = GetRegistration(team.TournamentId, team.OrganizationId);

            if (registration == null)
            {
                return SetTeamOrAdjudicatorResult.RegistrationNotFound;
            }

            if (team.Speaker.Count > 0)
            {
                // Check maximum number of speakers

                if (team.Speaker.Count > team.Tournament.TeamSize)
                {
                    return SetTeamOrAdjudicatorResult.TooManySpeakers;
                }

                // check for duplicate speakers in team
                var distinctSpeakers = team.Speaker.Distinct(new UserComparer());
                if (distinctSpeakers.Count() != team.Speaker.Count)
                {
                    return SetTeamOrAdjudicatorResult.SpeakerAlreadyInTeam;
                }

                // check if speakers are already in other team or adjudicator

                var adjudicators = GetAdjudicators(team.TournamentId);

                var tournamentSpeakers = GetSpeakers(team.TournamentId, team.Id);

                foreach (var speaker in team.Speaker)
                {
                    if (tournamentSpeakers.Any(tsp => tsp.Id == speaker.Id))
                    {
                        return SetTeamOrAdjudicatorResult.SpeakerAlreadyInOtherTeam;
                    }

                    if (adjudicators.Any(adj => adj.UserId == speaker.Id))
                    {
                        return SetTeamOrAdjudicatorResult.SpeakerAlreadyAdjudicator;
                    }
                }


            }

            team.UpdateTrackingData(user);

            // check if team already exists

            var savedTeam = GetTeam(team.Id);

            if (savedTeam == null)
            {
                // check if organization has too many teams

                var teamCountForOrganization = unitOfWork.GetRepository<Team>().Get(t =>
                    t.TournamentId == team.TournamentId && t.OrganizationId == team.OrganizationId).Count();

                if (teamCountForOrganization >= registration.TeamsPaid)
                {
                    return SetTeamOrAdjudicatorResult.TooManyTeams;
                }

                // Insert new team

                unitOfWork.GetRepository<Team>().Insert(team);
                unitOfWork.Save();

                return SetTeamOrAdjudicatorResult.TeamAdded;
            }

            unitOfWork.Detach(savedTeam);
            unitOfWork.GetRepository<Team>().Update(team);
            unitOfWork.Save();

            return SetTeamOrAdjudicatorResult.TeamUpdated;
        }