/*
Copyright (c) 2013, Matthew Malensek
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/
package jcrib;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import jcrib.cards.Card;
import jcrib.cards.Deck;
import jcrib.cards.Face;
import jcrib.cards.Hand;

public class Game {

    private static final Logger logger = Logger.getLogger("jcrib");

    public enum State { Cut, Crib, Play };

    private List<Player> players = new ArrayList<>();

    private State currentState;

    private int cuts;
    private Player turn;
    private Player dealer;
    private Hand crib;
    private Card starter;
    private Play playState;
    private Deck deck;

    public Game(Player player1, Player player2) {
        players.add(player1);
        players.add(player2);

        deck = new Deck();
        cuts = 0;
        startCut();
        turn = player1;
    }

    public static void deal(Deck deck, int numCards, Player... players) {
        deal(deck, numCards, players);
    }

    public static void deal(Deck deck, int numCards, Iterable<Player> players) {
        for (int i = 0; i < numCards; ++i) {
            for (Player player : players) {
                Card card = deck.removeCard();
                player.getHand().addCard(card);
            }
        }
    }
    private void startCut() {
        deck.shuffle();
        this.currentState = State.Cut;
    }

    private void startPlay() {
        deck = new Deck();
        deck.shuffle();

        int cards = 6;
        if (players.size() > 2) {
            cards = 5;
        }
        deal(deck, cards, players);

        crib = new Hand();
        currentState = State.Crib;
    }

    public Card drawStarter() {
        starter = deck.removeCard();
        if (starter.getFace() == Face.Jack) {
            dealer.addScore(new Score(Score.Type.Heels,
                        new Card[] { starter }, 2));
        }
        return starter;
    }

    public List<Score> playCard(Player player, int cardNumber) {
        if (logger.isLoggable(Level.INFO)) {
            logger.info(player.getName() + " plays card " + cardNumber);
        }

        Card card = player.getHand().removeCard(cardNumber);
        List<Score> scores = playState.playCard(player, card);
        player.addScores(scores);

        if (playState.isFinished()) {
            System.out.println("Round over!");
        } else {
            turn = playState.nextPlayableTurn(player);
        }

        return scores;
    }

    public void moveToCrib(Player player, int cardNumber)
    throws IllegalPlayException {
        if (logger.isLoggable(Level.INFO)) {
            logger.info(player.getName() + " moves card " + cardNumber
                    + " to crib");
        }

        if (cardNumber >= player.getHand().size()) {
            throw new IllegalPlayException("Invalid card index: " + cardNumber);
        }

        crib.addCard(player.getHand().removeCard(cardNumber));

        if (logger.isLoggable(Level.INFO)) {
            logger.info("Crib: " + crib.toString());
        }

        /* Crib is ready to go, start playing. */
        if (crib.size() == 4) {
            currentState = State.Play;
            playState = new Play(players);
            turn = playState.nextPlayableTurn(dealer);
        }
    }

    public void selectCutCard(Player player, int cardNumber)
    throws IllegalPlayException {
        if (cardNumber >= deck.size()) {
            cardNumber = deck.size() - 1;
        }

        player.setCutCard(deck.removeCard(cardNumber));
        cuts++;

        if (cuts == players.size()) {
            determineFirst();
        }
    }

    private boolean determineFirst() {
        int lowest = Integer.MAX_VALUE;
        boolean tie = false;
        Player first = null;

        for (Player player : players) {
            if (logger.isLoggable(Level.INFO)) {
                logger.info(player.getName() + " drew " + player.getCutCard());
            }

            int cardValue = player.getCutCard().getOrdinal();
            if (cardValue == lowest) {
                tie = true;
            } else if (cardValue < lowest) {
                lowest = cardValue;
                tie = false;
                first = player;
            }
        }

        if (!tie) {
            if (logger.isLoggable(Level.INFO)) {
                logger.info(first.getName() + " deals first");
            }

            dealer = first;
            startPlay();
            return true;
        } else {
            cuts = 0;
            return false;
        }
    }

    public List<Player> getPlayers() {
        return players;
    }

    public Game.State getState() {
        return currentState;
    }

    public Play getPlayState() {
        return playState;
    }

    public Player getCurrentPlayer() {
        return turn;
    }

    public Player getDealer() {
        return dealer;
    }
}

@@ -2656,30 +2656,29 @@
     %7D%0A%0A    p
-rivate
+ublic
  void startP

Allow shuffle by external method call