/*
 * An object of type Hand represents a hand of cards.  The
 * cards belong to the class Card.  A hand is empty when it
 * is created, and any number of cards can be added to it.
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class Hand {

  private List<Card> hand = new ArrayList<Card>();

  // Create a hand that is initially empty.
  public Hand() {
    hand = new ArrayList<Card>();
  }

  // Remove all cards from the hand, leaving it empty.
  public void clear() {
    hand.clear();
  }

  public void add(Card c) {
    assert c != null : "Cannot have empty cards";
    hand.add(c);
  }

  // Remove a card from the hand, if present.
  public void removeCard(Card c) {
    hand.remove(c);
  }

  public void remove(int position) {
    assert (0 <= position && position < hand.size()) : "Position does not exist in hand. ";
    hand.remove(position);
  }

  public int getCardCount() {
    return hand.size();
  }

  // Gets the card in a specified position in the hand without removing it.

  public Card get(int position) {
    assert (0 <= position && position < hand.size()) : "Position does not exist in hand. ";
    return hand.get(position);
  }

  /*
   * Sorts the cards in the hand so that cards of the same suit are grouped together, and within a
   * suit the cards are sorted by value. Note that aces are considered to have the lowest value, 1.
   */
  public void sortBySuit() {
    List<Card> newHand = new ArrayList<Card>();
    while (hand.size() > 0) {
      int pos = 0;  // Position of minimal card.
      Card c = hand.get(0);  // Minimal card.
      for (int i = 1; i < hand.size(); i++) {
        Card c1 = hand.get(i);
        if (c1.suit.lessThan(c.suit) ||
            (c1.suit.equals(c.suit)
                && c1.rank.lessThan(c.rank))) {
          pos = i;
          c = c1;
        }
      }
      hand.remove(pos);
      newHand.add(c);
    }
    hand = newHand;
  }

  /*
   * Sorts the cards in the hand so that cards of the same value are grouped together.  Cards with
   * the same value are sorted by suit.
   * Note that aces are considered to have the lowest value, 1 and the suits from
   * lowest to highest are SPADE,HEART,CLUB,DIAMOND.
   */
  public void sortByValue() {
    List<Card> newHand = new ArrayList<Card>();
    while (hand.size() > 0) {
      int pos = 0;  // Position of minimal card.
      Card c = hand.get(0);  // Minimal card.
      for (int i = 1; i < hand.size(); i++) {
        Card c1 = hand.get(i);
        if (c1.rank.lessThan(c.rank) ||
            (c1.rank.equals(c.rank)
                && c1.suit.lessThan(c.suit))) {
          pos = i;
          c = c1;
        }
      }
      hand.remove(pos);
      newHand.add(c);
    }
    hand = newHand;
  }

}