/* @(#)CardDeck.java 1.0  7 February 2005 */

/* Useful imports */

import edu.neu.ccs.*;
import edu.neu.ccs.gui.*;
import edu.neu.ccs.codec.*;
import edu.neu.ccs.console.*;
import edu.neu.ccs.filter.*;
import edu.neu.ccs.jpf.*;
import edu.neu.ccs.parser.*;
import edu.neu.ccs.pedagogy.*;
import edu.neu.ccs.quick.*;
import edu.neu.ccs.util.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;
import java.math.*;
import java.beans.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.regex.*;


public class CardDeck {

    public static final int decksize = CardImages.decksize;
    
    private Card[] card = new Card[decksize];
    
    private int[] permutation = null;
    
    
    /** Construct a shuffled card deck. */
    public CardDeck() {
        this(true);
    }
    
    
    /**
     * Construct a card deck.
     * 
     * If shuffle is true then shuffle the deck
     * otherwise return the deck with the cards in order.
     */
    public CardDeck(boolean shuffle) {
       int index = 0;
       
       for (int suit = Card.HEARTS; suit <= Card.CLUBS; suit++)
           for (int rank = Card.ACE; rank <= Card.KING; rank++) {
               card[index] = new Card(rank, suit);
               index++;
           }
       
       if (shuffle)
           shuffle();
       else
           placeInOrder();
    }
    
    
    /**
     * Place the cards in the deck in order by suit
     * hearts, diamonds, spades, clubs;
     * within each suit, rank the cards from ace to
     * king.
     */
    public void placeInOrder() {
        permutation = ProbStatTools.integerSequence(decksize);
    }
    
    
    /**
     * Shuffle the deck.
     */
    public void shuffle() {
        permutation = ProbStatTools.randomPermutation(decksize);
    }
    
    
    /**
     * Return the card at the given index.
     * 
     * If necessary, the index is forced into the range
     * from 0 to (decksize - 1).
     * 
     * @param index the card index
     * @return the card at the given index in the current order
     */
    public Card getCard(int index) {
        // error check
        
        index %= decksize;
        
        if (index < 0)
            index += decksize;
        
        return card[permutation[index]];
    }
}
