package primegui;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
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;
import javafx.stage.Stage;

/**
 * Version 1 : counts the primes below a limit in a background
 * task, so the window doesn't freeze. No progress reporting, no cancelling.
 */
public class BasicPrimeCounterApp extends Application {

	private TextField limitField_;
	private Label resultLabel_;

	@Override
	public void start ( Stage stage ) {
		Label limitLabel = new Label("Count primes below:");
		limitField_ = new TextField("20000000");

		Button countButton = new Button("Count");
		countButton.setOnAction(e -> startCount());

		resultLabel_ = new Label();

		HBox inputRow = new HBox(10,limitLabel,limitField_,countButton);
		VBox root = new VBox(10,inputRow,resultLabel_);
		root.setPadding(new Insets(15));

		stage.setScene(new Scene(root));
		stage.setTitle("Prime Counter (background task)");
		stage.show();
	}

	/** Runs on the FX thread, and returns as soon as the count has started. */
	private void startCount () {
		int limit = readLimit();
		if ( limit < 0 ) {
			return;
		}

		BasicPrimeCountTask task = new BasicPrimeCountTask(limit);
		task.setOnSucceeded(e -> showCount(limit,task.getValue()));
		task.setOnFailed(e -> resultLabel_.setText("Counting failed: " + task.getException().getMessage()));

		Thread thread = new Thread(task,"prime-count");
		thread.setDaemon(true); // closing the window ends the program
		thread.start();
	}

	private void showCount ( int limit, int count ) {
		resultLabel_.setText("Primes below " + limit + ": " + count);
	}

	/**
	 * @return the limit from the text field, or -1 (with a message) if it
	 *         isn't a whole number of at least 2
	 */
	private int readLimit () {
		try {
			int limit = Integer.parseInt(limitField_.getText().trim());
			if ( limit >= 2 ) {
				return limit;
			}
		} catch ( NumberFormatException e ) {}
		resultLabel_.setText("The limit must be a whole number of at least 2, e.g. 20000000");
		return -1;
	}

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

}
