package speiger.src.coreengine.utils.collections.pools;

import java.util.Collection;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Supplier;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectList;
import speiger.src.coreengine.utils.functions.Functions;

public class ThreadPool<T> implements IPool<T> {
	int cap;
	ObjectList<T> stack;
	Supplier<T> creator;
	Consumer<T> acceptor;
	
	public ThreadPool(int size, Supplier<T> creator) {
		this(size, creator, Functions.getVoidConsumer());
	}
	
	public ThreadPool(int size, Supplier<T> creator, Consumer<T> acceptor) {
		cap = size;
		stack = new ObjectArrayList<T>(size);
		this.creator = creator;
		this.acceptor = acceptor;
	}
	
	@Override
	public synchronized void accept(T t) {
		if(stack.size() < cap) {
			stack.add(t);
			acceptor.accept(t);
		}
	}
	
	@Override
	public synchronized void accept(T[] array) {
		int size = Math.min(array.length, cap - stack.size());
		if(size <= 0) return;
		stack.addAll(array, 0, size);
		for(int i = 0;i < size;acceptor.accept(array[i++]));
	}
	
	@Override
	public synchronized void accept(Collection<T> array) {
		int size = Math.min(array.size(), cap - stack.size());
		if(size <= 0) return;
		Iterator<T> iter = array.iterator();
		for(int i = 0;i < size && iter.hasNext();i++) {
			T next = iter.next();
			stack.add(next);
			acceptor.accept(next);
		}
	}
	
	@Override
	public synchronized T get() {
		return stack.isEmpty() ? creator.get() : stack.remove(stack.size() - 1);
	}
	
	@Override
	public synchronized T[] get(T[] array) {
		for(int i = 0,m = array.length;i < m;i++) {
			array[i] = stack.isEmpty() ? creator.get() : stack.remove(stack.size() - 1);
		}
		return array;
	}
}
