package de.szut.casino.blackjack;

import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class DeckService {
    private final Random random;

    public DeckService(Random random) {
        this.random = random;
    }

    public void initializeDeck(BlackJackGameEntity game) {
        for (Suit suit : Suit.values()) {
            for (Rank rank : Rank.values()) {
                CardEntity card = new CardEntity();
                card.setGame(game);
                card.setSuit(suit);
                card.setRank(rank);
                card.setCardType(CardType.DECK);
                game.getDeck().add(card);
            }
        }

        java.util.Collections.shuffle(game.getDeck(), random);
    }

    public CardEntity drawCardFromDeck(BlackJackGameEntity game) {
        if (game.getDeck().isEmpty()) {
            throw new IllegalStateException("Deck is empty");
        }

        return game.getDeck().removeFirst();
    }

    public void dealInitialCards(BlackJackGameEntity game) {
        for (int i = 0; i < 2; i++) {
            dealCardToPlayer(game);
        }

        dealCardToDealer(game);
    }

    public void dealCardToPlayer(BlackJackGameEntity game) {
        CardEntity card = drawCardFromDeck(game);
        card.setCardType(CardType.PLAYER);
        game.getPlayerCards().add(card);
    }

    public void dealCardToDealer(BlackJackGameEntity game) {
        CardEntity card = drawCardFromDeck(game);
        card.setCardType(CardType.DEALER);
        game.getDealerCards().add(card);
    }
}
