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