import java.util.OptionalLong;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * Klondike "New Game" window example as a complete application.
 */
public class NewGameApp extends Application {

	@Override
	public void start ( Stage stage ) {
		stage.setTitle("New Game");
		stage.setScene(new Scene(buildForm(stage)));
		stage.show();
	}

	private VBox buildForm ( Stage stage ) {
		// selection: exactly one of two
		RadioButton drawOne = new RadioButton("Draw 1");
		RadioButton drawThree = new RadioButton("Draw 3");
		ToggleGroup draw = new ToggleGroup();
		drawOne.setToggleGroup(draw);
		drawThree.setToggleGroup(draw);
		drawThree.setSelected(true);

		// selection: independent on/off, and one of many
		CheckBox timed = new CheckBox("Timed game");
		ComboBox<String> cardBack = new ComboBox<>();
		cardBack.getItems().addAll("Blue","Red","Forest");
		cardBack.setValue("Blue");

		// input: validated free text
		TextField seed = new TextField();
		seed.setPromptText("optional, e.g. 12345");
		Label seedError = new Label();

		// actions
		Button start = new Button("Start Game");
		start.setDefaultButton(true);
		Button cancel = new Button("Cancel");
		cancel.setCancelButton(true);
		cancel.setOnAction(e -> stage.close());
		start.setOnAction(e -> {
			try {
				OptionalLong seedValue = SeedParser.parse(seed.getText());
				seedError.setText("");
				if ( drawOne.isSelected() ) {
					startGame(1,timed.isSelected(),cardBack.getValue(),seedValue);
				} else {
					startGame(3,timed.isSelected(),cardBack.getValue(),seedValue);
				}
			} catch ( NumberFormatException ex ) {
				seedError.setText("Seed must be a whole number, e.g. 12345");
				seed.requestFocus();
			}
		});

		// layout
		HBox drawRow = new HBox(10,drawOne,drawThree);
		HBox buttons = new HBox(10,cancel,start);
		buttons.setAlignment(Pos.CENTER_RIGHT);
		VBox form =
		    new VBox(10,new Label("Draw:"),drawRow,timed,new Label("Card back:"),
		             cardBack,new Label("Deal seed:"),seed,seedError,buttons);
		form.setPadding(new Insets(15));
		return form;
	}

	/**
	 * Stand-in for starting a real game: reports the chosen settings. 
	 */
	private void startGame ( int drawCount, boolean isTimed, String back,
	                         OptionalLong seed ) {
		System.out.println("Starting game: draw " + drawCount + ", timed=" + isTimed
		    + ", card back=" + back + ", seed="
		    + (seed.isPresent() ? seed.getAsLong() : "random"));
	}

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