package org.luxons.sevenwonders.controllers;

import java.security.Principal;

import org.luxons.sevenwonders.actions.PrepareCardAction;
import org.luxons.sevenwonders.game.Game;
import org.luxons.sevenwonders.game.Player;
import org.luxons.sevenwonders.game.api.PlayerTurnInfo;
import org.luxons.sevenwonders.game.api.PreparedCard;
import org.luxons.sevenwonders.repositories.GameRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class GameController {

    private static final Logger logger = LoggerFactory.getLogger(GameController.class);

    private final SimpMessagingTemplate template;

    private final GameRepository gameRepository;

    @Autowired
    public GameController(SimpMessagingTemplate template, GameRepository gameRepository) {
        this.template = template;
        this.gameRepository = gameRepository;
    }

    @MessageMapping("/game/{gameId}/prepare")
    public void prepareCard(@DestinationVariable long gameId, PrepareCardAction action, Principal principal) {
        Game game = gameRepository.find(gameId);
        PreparedCard preparedCard = game.prepareCard(principal.getName(), action.getMove());
        logger.info("Game '{}': player {} prepared move {}", gameId, principal.getName(), action.getMove());

        if (game.areAllPlayersReady()) {
            game.playTurn();
            sendTurnInfo(game);
        } else {
            sendPreparedCard(preparedCard, game);
        }
    }

    private void sendPreparedCard(PreparedCard preparedCard, Game game) {
        for (Player player : game.getPlayers()) {
            String username = player.getUsername();
            template.convertAndSendToUser(username, "/topic/game/" + game.getId() + "/prepared", preparedCard);
        }
    }

    private void sendTurnInfo(Game game) {
        for (PlayerTurnInfo turnInfo : game.getCurrentTurnInfo()) {
            String username = turnInfo.getPlayer().getUsername();
            template.convertAndSendToUser(username, "/topic/game/" + game.getId() + "/turn", turnInfo);
        }
    }
}

@@ -176,52 +176,8 @@
 me;%0A
-import org.luxons.sevenwonders.game.Player;%0A
 impo
@@ -1826,114 +1826,8 @@
 ) %7B%0A
-        for (Player player : game.getPlayers()) %7B%0A            String username = player.getUsername();%0A    
     
@@ -1853,33 +1853,17 @@
 tAndSend
-ToUser(username, 
+(
 %22/topic/
@@ -1914,26 +1914,16 @@
 dCard);%0A
-        %7D%0A
     %7D%0A%0A 
@@ -2152,21 +2152,21 @@
 name, %22/
-topic
+queue
 /game/%22 

Fix subscription path for prepared cards and turns