package com.priess.se.tdd.thirtyone;


import java.util.Set;

import com.priess.se.tdd.thirtyone.Card.Color;
import com.priess.se.tdd.thirtyone.Card.Face;

public class ThirtyOneImpl implements ThirtyOne {

	@Override
	public boolean isOwnHandLosing(Hand own, Set<Hand> others) throws IllegalArgumentException {
		double ownValue = valueOfHand(own);

		// Search for any other hand with a lower value than the value of the own hand
		for (Hand other : others) {
			if (valueOfHand(other) < ownValue) {
				return false;
			}
		}
		return true;
	}

	@Override
	public double valueOfHand(Hand hand) throws IllegalArgumentException {

		// Check if hand is valid
		if (hand == null || hand.cards.size() != 3) {
			throw new IllegalArgumentException("Hand must have exactly 3 cards.");
		}

		// High card
		double handValue = 0;
		for (Card c : hand.cards) {
			int cardValue = c.face.value;
			if (cardValue > handValue) {
				handValue = cardValue;
			}
		}

		// Sum values of same color
		for (Color color : Color.values()) {
			int sum = 0;
			for (Card c : hand.cards) {
				if (c.color == color) {
					sum += c.face.value;
				}
			}
			if (sum > handValue) {
				handValue = sum;
			}
		}

		// Find triplet
		Card[] cards = new Card[3];
		cards = hand.cards.toArray(cards);
		if (cards[0].face == cards[1].face && cards[0].face == cards[2].face) {
			if (cards[0].face == Face.ASS) {
				handValue = 33;
			} else {
				handValue = 30.5;
			}
		}

		return handValue;
	}
}
