package alg.word;

import java.util.List;
import java.util.concurrent.RecursiveAction;

import data.Sentence;
import data.StatisticsNew;

public class ForkJoin extends RecursiveAction {
	private static final long serialVersionUID = 7711587510996456040L;

	private static final int ACCEPTABLE_SIZE = 1000;
	private List<Sentence> corpus;
	private StatisticsNew stats;
	private int start;
	private int end;


	/**
	 * Constructor for subproblems.
	 */
	private ForkJoin(List<Sentence> corpus, int start, int end, StatisticsNew stats) {
		this.corpus = corpus;
		this.start = start;
		this.end = end;
		this.stats = stats;
	}

	/**
	 * Default constructor for the initial problem
	 */
	public ForkJoin(List<Sentence> corpus, StatisticsNew stats) {
		this.corpus = corpus;
		this.start = 0;
		this.end = corpus.size();
		this.stats = stats;
	}

	private void computeDirectly() {
		List<Sentence> subCorpus = corpus.subList(start, end);
		WordLevel.calculateForAll(subCorpus, stats);
	}

	@Override
	protected void compute() {
		int subCorpusSize = end - start;

		if (subCorpusSize < ACCEPTABLE_SIZE) {
			computeDirectly();
		} else {
			int mid = start + subCorpusSize / 2;
			ForkJoin left = new ForkJoin(corpus, start, mid, stats);
			ForkJoin right = new ForkJoin(corpus, mid, end, stats);

			// fork (push to queue)-> compute -> join
			left.fork();
			right.fork();
			left.join();
			right.join();
		}
	}
}
