package auction.client;

import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

/**
 * Shows the client's copy of the auction, and redraws whenever it changes (it
 * listens to the AuctionState). Its buttons call the controller. Which controls
 * are enabled depends on the conversation state (the phase).
 */
public class AuctionView extends VBox implements AuctionStateListener {

	private AuctionState state_;

	private Label item_;
	private Label high_;
	private Label message_;
	private TextField name_;
	private Button join_;
	private TextField amount_;
	private Button bid_;
	private Button leave_;

	public AuctionView ( AuctionState state, AuctionController controller ) {
		super(12);
		state_ = state;
		setPadding(new Insets(16));

		item_ = new Label();
		item_.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
		high_ = new Label();
		high_.setStyle("-fx-font-size: 16px;");

		name_ = new TextField();
		name_.setPromptText("your name (one word)");
		join_ = new Button("Join");
		join_.setDefaultButton(true);
		join_.setOnAction(e -> controller.joinRequested(name_.getText()));

		amount_ = new TextField();
		amount_.setPrefColumnCount(6);
		bid_ = new Button("Bid");
		bid_.setOnAction(e -> controller.bidRequested(amount_.getText()));

		leave_ = new Button("Leave");
		leave_.setOnAction(e -> controller.leaveRequested());

		message_ = new Label();
		message_.setStyle("-fx-text-fill: #555;");

		getChildren().addAll(item_,high_,new HBox(8,name_,join_),
		                     new HBox(8,new Label("$"),amount_,bid_),leave_,
		                     message_);

		state_.addListener(this);
		stateChanged();
	}

	@Override
	public void stateChanged () {
		AuctionState.Phase phase = state_.getPhase();

		item_.setText(state_.getItem() == null ? "" : state_.getItem());
		if ( state_.getItem() == null ) {
			high_.setText("");
		} else if ( state_.getHighBidder() == null ) {
			high_.setText("no bids yet: opening bid $" + state_.getStartPrice());
		} else {
			high_.setText("high bid: $" + state_.getHighBid() + ", "
			    + (state_.isWinning() ? "you" : state_.getHighBidder()));
		}
		message_.setText(state_.getMessage());

		boolean notJoined = (phase == AuctionState.Phase.NOT_JOINED);
		boolean bidding = (phase == AuctionState.Phase.BIDDING);
		name_.setDisable(!notJoined);
		join_.setDisable(!notJoined);
		amount_.setDisable(!bidding);
		bid_.setDisable(!bidding || state_.isWinning()); // can't outbid yourself
		leave_.setDisable(!notJoined && !bidding);
		if ( bidding ) {
			amount_.setPromptText("at least " + state_.getMinimumBid());
			bid_.setDefaultButton(true);
			join_.setDefaultButton(false);
		}
	}

}
