package speiger.src.coreengine.core.events.bus;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.coreengine.core.events.api.Event;
import speiger.src.coreengine.core.events.api.EventPriority;
import speiger.src.coreengine.core.events.utility.Subscription;

public class Subscriptions {
	List<Subscription> subscriptions = new ObjectArrayList<>();
	EventBus owner;
	
	Subscriptions(EventBus owner) {
		this.owner = owner;
	}
	
	public <T extends Event> Subscriptions on(Class<T> clz, Consumer<T> event) {
		return on(clz, EventPriority.MEDIUM, event);
	}
	
	public <T extends Event> Subscriptions on(Class<T> clz, EventPriority priority, Consumer<T> event) {
		subscriptions.add(owner.register(clz, priority, event));
		return this;
	}

	public Subscriptions register(Object obj) {
		subscriptions.addAll(owner.register(obj, false));
		return this;
	}
	
	public Subscriptions registerRecursive(Object obj) {
		subscriptions.addAll(owner.register(obj, true));
		return this;
	}
	
	public void unsubscripe(Class<? extends Event> subType) {
		for(Iterator<Subscription> iter = subscriptions.iterator();iter.hasNext();) {
			Subscription sub = iter.next();
			if(!Objects.equals(sub.type(), subType)) continue;
			sub.unsubscribe();
			iter.remove();
		}
	}
	
	public void unsubscibe() {
		subscriptions.forEach(Subscription::unsubscribe);
		subscriptions.clear();
	}
}
