package auction.client;

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

/**
 * The client's copy of the auction, for showing: what the server has told it,
 * plus where this client's conversation has got (its phase). No sockets, no
 * message formats, no JavaFX. It changes only when the protocol tells it to,
 * and it tells its listeners (the views). Used only on the FX thread.
 */
public class AuctionState {

	/** The client's conversation states. */
	public enum Phase {
		WAITING_FOR_HELLO, NOT_JOINED, JOINING, BIDDING, BID_PENDING, ENDED,
		DISCONNECTED
	}

	private Phase phase_;
	private String name_; // this bidder's name; null until JOIN is sent
	private String item_; // null until ITEM arrives
	private int startPrice_;
	private String highBidder_; // null if there are no bids
	private int highBid_;
	private String message_; // a line for the user: what just happened
	private List<AuctionStateListener> listeners_;

	public AuctionState () {
		phase_ = Phase.WAITING_FOR_HELLO;
		name_ = null;
		item_ = null;
		startPrice_ = 0;
		highBidder_ = null;
		highBid_ = 0;
		message_ = "connecting…";
		listeners_ = new ArrayList<AuctionStateListener>();
	}

	public void addListener ( AuctionStateListener listener ) {
		listeners_.add(listener);
	}

	public void removeListener ( AuctionStateListener listener ) {
		listeners_.remove(listener);
	}

	private void changed () {
		for ( AuctionStateListener listener : listeners_ ) {
			listener.stateChanged();
		}
	}

	public Phase getPhase () {
		return phase_;
	}

	public void setPhase ( Phase phase ) {
		phase_ = phase;
		changed();
	}

	public String getName () {
		return name_;
	}

	public void setName ( String name ) {
		name_ = name;
		changed();
	}

	/** @return the item's description, or null if not known yet */
	public String getItem () {
		return item_;
	}

	public int getStartPrice () {
		return startPrice_;
	}

	public void setItem ( int startPrice, String item ) {
		startPrice_ = startPrice;
		item_ = item;
		changed();
	}

	/** @return the high bidder, or null if there are no bids */
	public String getHighBidder () {
		return highBidder_;
	}

	public int getHighBid () {
		return highBid_;
	}

	public void setHighBid ( int amount, String bidder ) {
		highBid_ = amount;
		highBidder_ = bidder;
		changed();
	}

	/** @return true if this client's bidder has the high bid */
	public boolean isWinning () {
		return name_ != null && name_.equals(highBidder_);
	}

	/**
	 * @return the smallest bid that could be accepted, as far as this copy knows
	 *         (the real high bid may already be higher)
	 */
	public int getMinimumBid () {
		if ( highBidder_ == null ) {
			return startPrice_;
		}
		return highBid_ + 1;
	}

	public String getMessage () {
		return message_;
	}

	public void setMessage ( String message ) {
		message_ = message;
		changed();
	}

}
