package auction.client;

import java.io.IOException;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 * A JavaFX client for the auction server. Connects to localhost 5003 unless
 * given a host and port: java auction.client.AuctionApp [host [port]]
 */
public class AuctionApp extends Application {

	private AuctionState state_;
	private AuctionProtocol protocol_;
	private ServerConnection connection_; // null until connected

	@Override
	public void start ( Stage stage ) {
		state_ = new AuctionState();
		protocol_ = new AuctionProtocol(state_);
		AuctionController controller = new AuctionController(state_,protocol_);
		AuctionView view = new AuctionView(state_,controller);

		stage.setScene(new Scene(view,420,300));
		stage.setTitle("Auction");
		stage.show();

		java.util.List<String> args = getParameters().getRaw();
		String host = (args.size() > 0 ? args.get(0) : "localhost");
		int port = (args.size() > 1 ? Integer.parseInt(args.get(1)) : 5003);
		connect(host,port);
	}

	/**
	 * Connects on a background thread: connecting can take a while, and the FX
	 * thread must not wait.
	 */
	private void connect ( String host, int port ) {
		Thread connector = new Thread(() -> {
			try {
				ServerConnection connection = new ServerConnection(host,port,protocol_);
				Platform.runLater(() -> {
					connection_ = connection;
					protocol_.setServer(connection);
					connection.start();
				});
			} catch ( IOException e ) {
				Platform.runLater(() -> {
					state_.setPhase(AuctionState.Phase.DISCONNECTED);
					state_.setMessage("couldn't connect to " + host + ":" + port);
				});
			}
		},"connector");
		connector.setDaemon(true);
		connector.start();
	}

	@Override
	public void stop () {
		// the window was closed: leave politely, then close the socket
		protocol_.quit();
		if ( connection_ != null ) {
			connection_.close();
		}
	}

	public static void main ( String[] args ) {
		launch(args);
	}

}
