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 0: counts the primes below a limit in the event handler, on the FX
 * thread, so the window freezes while it counts.
 */
public class FrozenPrimeCounterApp 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 -> count());

		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 (frozen)");
		stage.show();
	}

	/** Runs on the FX thread: nothing else happens until it returns. */
	private void count () {
		int limit;
		try {
			limit = Integer.parseInt(limitField_.getText().trim());
		} catch ( NumberFormatException e ) {
			resultLabel_.setText("The limit must be a whole number, e.g. 20000000");
			return;
		}

		int count = 0;
		for ( int n = 2 ; n < limit ; n++ ) {
			if ( PrimeCounter.isPrime(n) ) {
				count++;
			}
		}
		resultLabel_.setText("Primes below " + limit + ": " + count);
	}

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

}
