package primegui;

import javafx.concurrent.Task;

/**
 * Counts the primes below a limit on a background thread, reporting progress
 * and stopping early if cancelled.
 */
public class PrimeCountTask extends Task<Integer> {

	private int limit_;

	/**
	 * @param limit count the primes below this; read from the UI on the FX
	 *          thread
	 */
	public PrimeCountTask ( int limit ) {
		limit_ = limit;
	}

	@Override
	protected Integer call () {
		int count = 0;
		for ( int n = 2 ; n < limit_ ; n++ ) {
			if ( n % 10000 == 0 ) {
				if ( isCancelled() ) {
					return null;
				}
				updateProgress(n,limit_);
				updateMessage("Counting... " + n + " of " + limit_ + " checked");
			}
			if ( PrimeCounter.isPrime(n) ) {
				count++;
			}
		}
		return count;
	}

}
