package oving4.card;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

public class CardHandTest {

	private CardHand cardHand;

	private static void checkHand(CardHand hand, String deckAsString) {
		String[] toStrings = deckAsString.split(",");
		assertEquals(toStrings.length, hand.getCardCount(),
				"The number of cards in the hand was incorrect");

		int i = 0;

		for (String toString : toStrings) {
			Card card = hand.getCard(i);
			String cardString = String.valueOf(card.getSuit()) + card.getFace();
			assertEquals(toString, cardString, String.format(
					"The card at position %d was incorrect. The hand should have contained %s",
					i + 1, toStrings));

			i++;
		}
	}

	@BeforeEach
	public void setUp() {
		cardHand = new CardHand();
	}

	@Test
	@DisplayName("Check that CardHand is initialized to empty")
	public void testConstructor() {
		CardDeck deck = new CardDeck(2);
		deck.deal(cardHand, 3);
		CardHandTest.checkHand(cardHand, "C2,C1,D2");
	}

	@Test
	@DisplayName("Test the addCard method")
	public void testAddCard() {
		CardDeck deck = new CardDeck(2);
		deck.deal(cardHand, 3);
		CardHandTest.checkHand(cardHand, "C2,C1,D2");

		cardHand.addCard(new Card('H', 1));
		CardHandTest.checkHand(cardHand, "C2,C1,D2,H1");

		assertThrows(IllegalArgumentException.class, () -> {
			cardHand.addCard(null);
		}, "Cannot add null card");
	}

	@Test
	@DisplayName("Test the deal and play methods")
	public void testDealPlay() {
		CardDeck deck = new CardDeck(2);
		deck.deal(cardHand, 3);
		CardHandTest.checkHand(cardHand, "C2,C1,D2");

		cardHand.play(1);
		CardHandTest.checkHand(cardHand, "C2,D2");

		cardHand.play(0);
		CardHandTest.checkHand(cardHand, "D2");

		cardHand.play(0);
		assertEquals(cardHand.getCardCount(), 0);
	}
}
