Skip to content

Commit

Permalink
lagt til hente totalscore, høyeste og laveste
Browse files Browse the repository at this point in the history
  • Loading branch information
tofiksa committed Nov 24, 2024
1 parent a0e2c90 commit 26d99c1
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 25 deletions.
10 changes: 10 additions & 0 deletions src/main/java/no/josefushighscore/controller/GameController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import no.josefushighscore.dto.ScoreDto;
import no.josefushighscore.exception.InvalidJwtAuthenticationException;
import no.josefushighscore.service.GameService;
import no.josefushighscore.service.ScoreService;
import no.josefushighscore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
Expand All @@ -24,6 +25,9 @@ public class GameController {
@Autowired
private GameService gameService;

@Autowired
private ScoreService scoreService;

@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping("/id")
public ResponseEntity getGameId(@AuthenticationPrincipal UserDetails userDetails) throws InvalidJwtAuthenticationException {
Expand All @@ -35,4 +39,10 @@ public ResponseEntity getGameId(@AuthenticationPrincipal UserDetails userDetails
public ResponseEntity postScore(@AuthenticationPrincipal UserDetails userDetails, @RequestBody ScoreDto scoreDto) throws InvalidJwtAuthenticationException {
return ok(gameService.updateScore(userDetails.getUsername(), scoreDto));
}

@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping("/score")
public ResponseEntity getScore(@AuthenticationPrincipal UserDetails userDetails) throws InvalidJwtAuthenticationException {
return ok(scoreService.getTotalScoreForUser(userDetails.getUsername()));
}
}
22 changes: 11 additions & 11 deletions src/main/java/no/josefushighscore/dto/GameDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@

import no.josefushighscore.model.Score;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class GameDto {

private Long gameId;
private Long userId;
private String username;
private LocalDate createdAt;
private LocalDate updatedAt;
private LocalDate gameEndTime;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime gameEndTime;
private Score score;

public GameDto(Score score, Long gameId, Long userId, String username, LocalDate createdAt, LocalDate updatedAt, LocalDate gameEndTime) {
public GameDto(Score score, Long gameId, Long userId, String username, LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime gameEndTime) {
this.gameId = gameId;
this.userId = userId;
this.username = username;
Expand Down Expand Up @@ -56,27 +56,27 @@ public void setUsername(String username) {
this.username = username;
}

public LocalDate getCreatedAt() {
public LocalDateTime getCreatedAt() {
return createdAt;
}

public void setCreatedAt(LocalDate createdAt) {
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}

public LocalDate getUpdatedAt() {
public LocalDateTime getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(LocalDate updatedAt) {
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}

public LocalDate getGameEndTime() {
public LocalDateTime getGameEndTime() {
return gameEndTime;
}

public void setGameEndTime(LocalDate gameEndTime) {
public void setGameEndTime(LocalDateTime gameEndTime) {
this.gameEndTime = gameEndTime;
}
}
20 changes: 10 additions & 10 deletions src/main/java/no/josefushighscore/model/Game.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import jakarta.persistence.*;
import lombok.Data;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Entity
@Table(name="`game`")
Expand All @@ -24,23 +24,23 @@ public class Game {
private User user;

@Column(name="`created_at`")
LocalDate createdAt;
LocalDateTime createdAt;

@Column(name="`updated_at`")
LocalDate updatedAt;
LocalDateTime updatedAt;

@Column(name="`game_end_time`")
LocalDate gameEndTime;
LocalDateTime gameEndTime;

public Game() {

}

public LocalDate getGameEndTime() {
public LocalDateTime getGameEndTime() {
return gameEndTime;
}

public void setGameEndTime(LocalDate gameEndTime) {
public void setGameEndTime(LocalDateTime gameEndTime) {
this.gameEndTime = gameEndTime;
}

Expand Down Expand Up @@ -72,19 +72,19 @@ public void setUser(User user) {
this.user = user;
}

public LocalDate getCreatedAt() {
public LocalDateTime getCreatedAt() {
return createdAt;
}

public void setCreatedAt(LocalDate createdAt) {
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}

public LocalDate getUpdatedAt() {
public LocalDateTime getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(LocalDate updatedAt) {
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}
2 changes: 2 additions & 0 deletions src/main/java/no/josefushighscore/register/GameRegister.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
Expand All @@ -14,4 +15,5 @@ public interface GameRegister extends JpaRepository<Game,Long> {
Optional<Game> findLatestByUser_UserId(Long userId);
Optional<Game> findByGameId(Long gameId);
Page<Game> findByUser_UserId(Long userId, Pageable pageable);
List<Game> findByUser_UserId(Long userId);
}
6 changes: 2 additions & 4 deletions src/main/java/no/josefushighscore/service/GameService.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Optional;

Expand All @@ -40,8 +39,8 @@ public Game getGameDetails(String username) {
Game game = new Game();
game.setUser(currentUser.orElseThrow(
() -> new UsernameNotFoundException("Username " + username + " not found")));
game.setCreatedAt(LocalDate.now());
game.setGameEndTime(LocalDate.now());
game.setCreatedAt(LocalDateTime.now());
game.setGameEndTime(LocalDateTime.now());
gameRegister.save(game);

return game;
Expand Down Expand Up @@ -87,7 +86,6 @@ public Score updateScore(String username, ScoreDto scoreDto) {
// Game was not found
}


return score;
}

Expand Down
83 changes: 83 additions & 0 deletions src/main/java/no/josefushighscore/service/ScoreService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package no.josefushighscore.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import no.josefushighscore.model.Game;
import no.josefushighscore.model.Score;
import no.josefushighscore.model.User;
import no.josefushighscore.register.GameRegister;
import no.josefushighscore.register.UserRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

@Service
public class ScoreService {

private final GameRegister gameRegister;
private final UserRegister userRegister;

private final Logger LOG = LoggerFactory.getLogger(ScoreService.class);

public ScoreService (GameRegister gameRegister, UserRegister userRegister) {
this.gameRegister = gameRegister;
this.userRegister = userRegister;
}

public ObjectNode getTotalScoreForUser (String username) {

List<Game> getAllGamesForUser = this.gameRegister.findByUser_UserId(getUserId(username));
Stream<Score> allGamesUserHasScoreOn = getAllGamesForUser.stream()
.map(Game::getScoreId)
.filter(Objects::nonNull) // Filter out null Score objects
.distinct();

Long totalScore = allGamesUserHasScoreOn
.mapToLong(score -> score.getScore() != null ? score.getScore() : 0L) // Handle null scores
.sum();
LOG.info("This player scored {} points for player {}", totalScore, username);

ObjectMapper mapper = new ObjectMapper();
ObjectNode response = mapper.createObjectNode();
response.put("totalScore", totalScore);
response.put("gameStats",getHighestAndLowestScores(getAllGamesForUser));

return response;
}

private Long getUserId (String username) {
Optional<User> getUserId = this.userRegister.findByUsername(username);
return getUserId.orElseThrow().getUserId();
}

private ObjectNode getHighestAndLowestScores(List<Game> getAllGamesForUser) {

Stream<Score> scores = getAllGamesForUser.stream()
.map(Game::getScoreId)
.filter(Objects::nonNull) // Filter out null Score objects
.distinct();

LongSummaryStatistics stats = scores
.filter(score -> score != null)
.map(Score::getScore)
.filter(score -> score != null)
.mapToLong(Long::longValue)
.filter(score -> score >= 0)
.summaryStatistics();

ObjectMapper mapper = new ObjectMapper();
ObjectNode response = mapper.createObjectNode();
response.put("highestScore", stats.getCount() > 0 ? stats.getMax() : 0L);
response.put("lowestScore", stats.getCount() > 0 ? stats.getMin() : 0L);

return response;
}


}

0 comments on commit 26d99c1

Please sign in to comment.