/*******************************************************************************
 * Copyright (c) 2010 Attila Kovacs <attila_kovacs@post.harvard.edu>.
 * All rights reserved. 
 * 
 * This file is part of crush.
 * 
 *     crush is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     crush is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with crush.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila_kovacs@post.harvard.edu> - initial API and implementation
 ******************************************************************************/
package util;

import java.util.*;

public abstract class ParallelOp<Type> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3231222039535248732L;
	int maxThreads;
	private Vector<ProcessingThread> queue = new Vector<ProcessingThread>();
	
	public ParallelOp(int maxThreads) {
		this.maxThreads = maxThreads;
	}
		
	public synchronized void process(Collection<Type> data) throws InterruptedException {
		// Limit the threads to the available data
		final int threads = Math.min(maxThreads, data.size());
		
		if(!queue.isEmpty()) throw new IllegalStateException("Queue not empty.");
		
		queue.ensureCapacity(threads);
	
		for(int i=0; i<threads; i++) queue.add(new ProcessingThread());
		divide(data, (ProcessingThread[]) queue.toArray());
	
		for(ProcessingThread thread : queue) thread.run();
		
		while(!queue.isEmpty()) wait();
	}
	
	protected void divide(Collection<Type> data, ProcessingThread[] processors) {
		int i=0;
		for(Type entry : data) {
			processors[i++].add(entry);
			i %= processors.length; 
		}		
	}
	
	private synchronized void checkout(ProcessingThread thread) {
		queue.remove(thread);
		notifyAll();
	}
	
	public abstract void process(Type data);
	
	private class ProcessingThread extends ArrayList<Type> implements Runnable {			
		/**
		 * 
		 */
		private static final long serialVersionUID = -3973614679104705385L;

		public void run() {
			for(Type entry : this) process(entry);
			checkout(this);
		}
	}
	
	
}
