package eu.jonahbauer.wizard.core.states.round;

import eu.jonahbauer.wizard.common.messages.observer.HandMessage;
import eu.jonahbauer.wizard.common.model.Card;
import eu.jonahbauer.wizard.core.Game;
import eu.jonahbauer.wizard.core.states.GameData;
import eu.jonahbauer.wizard.core.states.GameState;
import eu.jonahbauer.wizard.core.model.deck.Deck;

import java.util.*;

import static eu.jonahbauer.wizard.core.states.GameData.*;

public final class Dealing extends RoundState {

    public Dealing(GameData data) {
        super(data);
    }

    @Override
    public Optional<GameState> onEnter(Game game) {
        Deck deck = new Deck(game.getConfig().cards());
        deck.shuffle(game.getRandom());

        var hands = new HashMap<UUID, List<Card>>();

        int round = get(ROUND);
        int playerCount = getPlayerCount();
        int cardCount = round + 1;
        for (int i = 1; i <= playerCount; i++) {
            int player = (round + i) % playerCount;
            hands.put(getPlayer(player), deck.draw(cardCount));
        }

        for (UUID player : get(PLAYERS)) {
            game.notify(player, new HandMessage(player, hands.get(player).stream().toList()));
        }

        Card trumpCard = deck.draw();
        return sync(
                getData().with(
                        HANDS, Map.copyOf(hands),
                        TRUMP_CARD, trumpCard
                ),
                DeterminingTrump::new
        );
    }
}
