package com.pkrharrison.tablegen.hands;

import com.pkrharrison.gameplay.Card;

public final class Pair extends RankedHand {

	private Card.Rank pair; // rank of the single pair
	private int kickerIndex; 

	private Pair(Card[] cards) {
		super(cards);
	}

	/**
	 * 
	 * @param cards
	 *            5 card hand containing a pair
	 * @param p
	 *            the index in cards that has one of the cards in the pair
	 * @param kickerPos
	 *            the indices in cards of the kickers
	 * @return an array details where details[0] is the rank of the pair, and
	 *         details[1..3] are the kicker ranks in descending order
	 * 
	 */
	private static Card.Rank extractPairDetails(Card[] cards, int p, int[] kickerPos, Card.Rank[] kickers) {
		for (int i = 0; i < kickerPos.length; i++) {
			 kickers[i] = cards[kickerPos[i]].rank();
		}
		return cards[p].rank();
	}

	public static Pair newHand(Card[] cards) {

		Card.Rank[] kickers = new Card.Rank[3];
		Card.Rank pair; 
		if (cards[0].rank() == cards[1].rank()) {
			// XXABC
			pair = extractPairDetails(cards, 0, new int[] { 2, 3, 4 }, kickers);
		} else if (cards[1].rank() == cards[2].rank()) {
			// AXXBC
			pair = extractPairDetails(cards, 1, new int[] { 0, 3, 4 }, kickers);
		} else if (cards[2].rank() == cards[3].rank()) {
			// ABXXC
			pair = extractPairDetails(cards, 2, new int[] { 0, 1, 4 }, kickers);
		} else if (cards[3].rank() == cards[4].rank()) {
			// ABCXX
			pair = extractPairDetails(cards, 3, new int[] { 0, 1, 2 }, kickers);
		} else {
			return null;
		}

		Pair hand = new Pair(cards);
		hand.pair = pair;		
		hand.kickerIndex = RankedHand.getKickerIndex(kickers); 
		return hand;

	}


	@Override
	public int compare(StraightFlush hand) {
		return -1;
	}

	@Override
	public int compare(Quads hand) {
		return -1;
	}

	@Override
	public int compare(FullHouse hand) {
		return -1;
	}

	@Override
	public int compare(Flush hand) {
		return -1;
	}

	@Override
	public int compare(Straight hand) {
		return -1;
	}

	@Override
	public int compare(ThreeOfAKind hand) {
		return -1;
	}

	@Override
	public int compare(TwoPair hand) {
		return -1;
	}

	@Override
	public int compare(Pair hand) {
		if (this.pair.compareTo(hand.pair) == 0) {
			return Integer.compare(this.kickerIndex, hand.kickerIndex);  
		}
		return this.pair.compareTo(hand.pair); 
	}


	@Override
	public int compare(HighCard hand) {
		return 1;
	}

	@Override
	public int compareTo(RankedHand rh) {
		return -1 * rh.compare(this);
	}

}
