package hdm.mi.sthbackend.service; import hdm.mi.sthbackend.exeptions.*; import hdm.mi.sthbackend.mapper.ModelToDTOMapper; import hdm.mi.sthbackend.model.*; import hdm.mi.sthbackend.repository.ITournamentRepository; import lombok.AllArgsConstructor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service @AllArgsConstructor public class TournamentService { private final Logger log = LogManager.getLogger(TournamentService.class); ITournamentRepository tournamentRepository; @Autowired ModelToDTOMapper mapper; public UUID addPlayerToTeam(UUID tournamentId, UUID teamId, String playerName) throws TournamentIdNotFoundException, TeamIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Team team = Optional.ofNullable(tournament.getTeams() .get(teamId)) .orElseThrow(() -> new TeamIdNotFoundException(teamId)); Player newPlayer = new Player(UUID.randomUUID(), playerName); team.getTeamMembers() .put(newPlayer.getPlayerId(), newPlayer); tournamentRepository.save(tournament); log.debug("Player " + newPlayer.getPlayerId() + " added to Team " + teamId + " of Tournament " + tournamentId); return newPlayer.getPlayerId(); } /* Wie gehen wir damit um, wenn zwei Player denselben Namen haben? Also: Stefan vs Stefan = Stefan gewinnt Sollte man hier in den Methoden das ausschließen und dann geben die Spieler ihren ersten Buchstaben vom Nachnamen an? z.B. Stefan S. vs Stefan w. oder geben wir die UUID auch mit an zum PlayerName */ public void removePlayerFromTeam(UUID tournamentId, UUID teamId, UUID playerId) throws PlayerIdNotFoundException, TeamIdNotFoundException, TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Team team = Optional.ofNullable(tournament.getTeams() .get(teamId)) .orElseThrow(() -> new TeamIdNotFoundException(teamId)); try { team.getTeamMembers() .remove(playerId); } catch (NullPointerException e) { throw new PlayerIdNotFoundException(playerId); } tournamentRepository.save(tournament); log.debug("Player " + playerId + " removed from Team " + teamId); } /* Kann es passieren, dass hier bei der Methode removePlayerFromTeam() es den Player gar nicht gibt? und dann eine PlayerIdNotFoundException geworfen werden muss? oder ist durch die Übergabe von UUID playerId schon safe die playerId vorhanden */ public UUID updatePlayerName(UUID tournamentId, UUID teamId, UUID playerId, String newPlayerName) throws PlayerIdNotFoundException, TournamentIdNotFoundException, TeamIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Team team = Optional.ofNullable(tournament.getTeams() .get(teamId)) .orElseThrow(() -> new TeamIdNotFoundException(teamId)); Player player = Optional.ofNullable(team.getTeamMembers() .get(playerId)) .orElseThrow(() -> new PlayerIdNotFoundException(playerId)); player.setName(newPlayerName); tournamentRepository.save(tournament); return playerId; } public UUID createAndAddTeamToTournament(UUID tournamentId, String teamName) throws TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Team newTeam = new Team(teamName); tournament.getTeams() .put(newTeam.getTeamId(), newTeam); tournamentRepository.save(tournament); return newTeam.getTeamId(); } public UUID deleteAndRemoveTeamFromTournament(UUID tournamentId, UUID teamId) throws TournamentIdNotFoundException, TeamIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); try { tournament.getTeams() .remove(teamId); } catch (NullPointerException e) { throw new TeamIdNotFoundException(tournamentId); } tournamentRepository.save(tournament); log.debug("Team " + teamId + " added to Tournament " + tournamentId); return teamId; } public Tournament createTournament(Tournament tournament) { tournamentRepository.insert(tournament); log.info("created Tournament " + tournament.getTournamentId()); return tournament; } public UUID determineWinner(UUID tournamentId, int bracketRound, UUID matchId ) throws MatchIdNotFoundException, WinnerNotDeterminedException, TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Match match = Optional.ofNullable(tournament.getBracket() .get(bracketRound) .getMatches() .get(matchId)) .orElseThrow(() -> new MatchIdNotFoundException(matchId)); UUID winnerTeamId = null; Integer winner = Integer.MIN_VALUE; boolean draw = false; for (Map.Entry<UUID, Integer> entry : match.getTeamScores() .entrySet()) { if (entry.getValue() >= winner) { winner = entry.getValue(); winnerTeamId = entry.getKey(); draw = false; } else if (winner.equals(entry.getValue())) { draw = true; } } if (draw) { throw new WinnerNotDeterminedException("Match id " + matchId + " is a draw"); } match.setWinnerTeamId(winnerTeamId); tournamentRepository.save(tournament); log.debug("The Winner " + winnerTeamId + " is determined for Match " + matchId); return winnerTeamId; } public Tournament assignTeamToMatch(UUID tournamentId, int bracketRound, UUID matchId, UUID teamId, int score) throws TournamentIdNotFoundException, MatchIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); try { tournament .getBracket() .get(bracketRound) .getMatches() .get(matchId) .getTeamScores() .put(teamId, score); } catch (Exception e) { throw new MatchIdNotFoundException(matchId); } tournamentRepository.save(tournament); log.debug("Team " + teamId + " assign to Match " + matchId); return tournament; } public void updateScore(UUID tournamentId, int bracketRound, UUID matchId, UUID teamId, int newScore) throws MatchIdNotFoundException, TeamIdNotFoundException, TournamentIdNotFoundException, BracketRoundNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); BracketRound bracket = Optional.ofNullable(tournament.getBracket() .get(bracketRound)) .orElseThrow(() -> new BracketRoundNotFoundException(bracketRound)); Match match = Optional.ofNullable(bracket.getMatches() .get(matchId)) .orElseThrow(() -> new MatchIdNotFoundException(matchId)); if (!match.getTeamScores() .containsKey(teamId)) { throw new TeamIdNotFoundException(teamId); } match.getTeamScores() .put(teamId, newScore); tournamentRepository.save(tournament); log.debug("Score of Team " + teamId + " updated to " + newScore); } public UUID updateTeamName(UUID tournamentId, UUID teamId, String newTeamName) throws TeamIdNotFoundException, TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Team team = Optional.ofNullable(tournament.getTeams() .get(teamId)) .orElseThrow(() -> new TeamIdNotFoundException(teamId)); team.setTeamName(newTeamName); tournamentRepository.save(tournament); log.debug("Teamname of " + teamId + " updated to " + newTeamName); return teamId; } public UUID updateTournamentName(UUID tournamentId, String newTournamentName) throws TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); tournament.setTournamentName(newTournamentName); tournamentRepository.save(tournament); log.debug("Tournament Name for TournamentID " + tournamentId + " updated to " + newTournamentName); return tournamentId; } public Tournament getTournament(UUID tournamentId) throws TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); log.debug(tournament + "is found"); return tournament; } public Tournament deleteTournament(UUID tournamentId) throws TournamentIdNotFoundException { Tournament tournamentToDelete = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); tournamentRepository.delete(tournamentToDelete); log.debug("Tournament " + tournamentId + " has been deleted"); return tournamentToDelete; } public Tournament createBracket(UUID tournamentId) throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Map<UUID, Team> teams = tournament.getTeams(); if (teams.size() < 2) { throw new InsufficientTeamsException(tournamentId); } // log zur Basis 2 von der Anzahl der Teams (aufgerundet) int roundCount = (int) Math.ceil(Math.log(teams.size()) / Math.log(2)); if (tournament.getBracket() .isEmpty()) { tournament.setBracket(new ArrayList<>()); for (int i = 0; i < roundCount; i++) { // richtige Anzahl an BracketRounds hinzufügen tournament.getBracket() .add(new BracketRound(i)); // anzahl der matches errechnen int matchCount = (int) (Math.pow(2, roundCount)) / (int) Math.pow(2, i + 1); for (int j = 0; j < matchCount; j++) { // matches hinzufügen UUID matchId = UUID.randomUUID(); tournament.getBracket() .get(i) .getMatches() .put(matchId, new Match(matchId)); } } } else { throw new BracketAlreadyInitializedException(tournamentId); } Tournament linkedTournament = linkMatchesInNextRound(tournament); tournamentRepository.save(linkedTournament); return linkedTournament; } private Tournament linkMatchesInNextRound(Tournament tournament) { int timesUsed = 0; Map<UUID, Match> nextRoundMatches; for (int i = 0; i < tournament.getBracket() .size() - 1; i++) { nextRoundMatches = tournament.getBracket() .get(i + 1) .getMatches(); List<UUID> nextRoundMatchIds = nextRoundMatches.keySet() .stream() .toList(); for (Map.Entry<UUID, Match> entry : tournament.getBracket() .get(i) .getMatches() .entrySet()) { UUID nextMatch = nextRoundMatchIds.get(0); entry.getValue() .setNextMatchId(nextMatch); if (timesUsed > 0) { nextRoundMatchIds.removeFirst(); timesUsed = 0; } else { timesUsed += 1; } } } return tournament; } public Tournament fillBracketRandom(UUID tournamentId) throws TournamentIdNotFoundException { Tournament tournament = tournamentRepository.findById(tournamentId) .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId)); Map<UUID, Team> teams = tournament.getTeams(); Random random = new Random(); for (int i = 0; i < 2; i++) { for (Match match : tournament.getBracket() .get(0) .getMatches() .values()) { if (!teams.isEmpty()) { int teamIndex = random.nextInt(0, teams.size()); UUID randomTeamId = teams.keySet() .stream() .toList() .get(teamIndex); match.getTeamScores() .put(teams.get(randomTeamId) .getTeamId(), 0); teams.remove(randomTeamId); } else { break; } } } tournamentRepository.save(tournament); return tournament; } /* Weitere Methoden: UpdateTeamScore Marius Tunier beenden GetTournament Leon DeleteTournament Leon User Mattis */ }