package auction.client;

/**
 * Turns the user's gestures into intentions: it validates what the user typed,
 * then asks the protocol to join, bid or leave. It knows no message syntax and
 * no sockets. Used only on the FX thread (the view's event handlers call it).
 */
public class AuctionController {

	private AuctionState state_;
	private AuctionProtocol protocol_;

	public AuctionController ( AuctionState state, AuctionProtocol protocol ) {
		state_ = state;
		protocol_ = protocol;
	}

	/** The user clicked Join with name typed in the name box. */
	public void joinRequested ( String name ) {
		name = name.trim();
		if ( name.isEmpty() || name.contains(" ") ) {
			state_.setMessage("a name is one word, with no spaces");
			return;
		}
		protocol_.join(name);
	}

	/** The user clicked Bid with amount typed in the amount box. */
	public void bidRequested ( String amount ) {
		int dollars;
		try {
			dollars = Integer.parseInt(amount.trim());
		} catch ( NumberFormatException e ) {
			state_.setMessage("a bid is a whole number of dollars");
			return;
		}
		// Safe to refuse: the high bid only goes up, so a bid below the
		// minimum this copy shows can't succeed, however stale the copy is.
		// A bid above it may still be refused; the server decides.
		if ( dollars < state_.getMinimumBid() ) {
			state_.setMessage("bid at least $" + state_.getMinimumBid());
			return;
		}
		protocol_.bid(dollars);
	}

	/** The user clicked Leave. */
	public void leaveRequested () {
		protocol_.quit();
	}

}
