package wk.eofextensions;

import com.webobjects.eocontrol.EOObjectStoreCoordinator;
import com.webobjects.foundation.NSMutableArray;

import er.extensions.foundation.ERXProperties;
import er.extensions.foundation.ERXRoundRobinCollection;

/**
 * A class that manages a pool of object store coordinators.
 * The initial requirement was to have a pool of OSC's that can be
 * shared among background tasks since we know that intense EOF activity
 * can block the OSC, we don't want to use the default OSC in background tasks.
 * 
 * @author kieran
 *
 */
public class WKTaskObjectStoreCoordinatorPool {
	private static class Pool {
		static final ERXRoundRobinCollection<EOObjectStoreCoordinator> FIELD = initializePool();
		
		static ERXRoundRobinCollection<EOObjectStoreCoordinator> initializePool() {
			int maxCoordinators = ERXProperties.intForKeyWithDefault("wk.eofextensions.WKTaskObjectStoreCoordinatorPool.maxCoordinators", 1);
			NSMutableArray<EOObjectStoreCoordinator> coordinators = new NSMutableArray<EOObjectStoreCoordinator>(maxCoordinators);
			for (int i = 0; i < maxCoordinators; i++) {
				int poolItemID = i + 1;
				coordinators.add(new WKObjectStoreCoordinator(true, "TaskPool-" + poolItemID + "/" + maxCoordinators));
			}
			return new ERXRoundRobinCollection<EOObjectStoreCoordinator>(coordinators.immutableClone());
		}
	}
	
	/**
	 * @return a OSC from the pool in Round Robin fashion
	 */
	public static EOObjectStoreCoordinator objectStoreCoordinator() {
		return Pool.FIELD.next();
	}

}
