package speiger.src.coreengine.rendering.input.bindings.utils;

import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;

import speiger.src.collections.ints.maps.impl.hash.Int2ObjectLinkedOpenHashMap;
import speiger.src.collections.ints.maps.interfaces.Int2ObjectMap;
import speiger.src.collections.objects.sets.ObjectLinkedOpenHashSet;
import speiger.src.coreengine.rendering.input.bindings.InputBinding;

public class BindingRegistry
{
	Map<BindingType, Int2ObjectMap<Set<InputBinding>>> handlers = new EnumMap<BindingType, Int2ObjectMap<Set<InputBinding>>>(BindingType.class);
	
	public void registerBinding(InputBinding binding)
	{
		Int2ObjectMap<Set<InputBinding>> bindings = handlers.get(binding.getInputType());
		if(bindings == null)
		{
			bindings = new Int2ObjectLinkedOpenHashMap<Set<InputBinding>>();
			handlers.put(binding.getInputType(), bindings);
		}
		Set<InputBinding> entries = bindings.get(binding.getKey());
		if(entries == null)
		{
			entries = new ObjectLinkedOpenHashSet<InputBinding>();
			bindings.put(binding.getKey(), entries);
		}
		entries.add(binding);
	}
	
	public void removeBinding(InputBinding binding)
	{
		Int2ObjectMap<Set<InputBinding>> bindings = handlers.get(binding.getInputType());
		if(bindings == null)
		{
			return;
		}
		Set<InputBinding> entries = bindings.get(binding.getKey());
		if(entries.remove(binding) && entries.isEmpty())
		{
			bindings.remove(binding.getKey());
			if(bindings.isEmpty())
			{
				handlers.remove(binding.getInputType());
			}
		}
	}
	
	public void updatePressing(BindingType type, int key, boolean pressed)
	{
		Int2ObjectMap<Set<InputBinding>> bindings = handlers.get(type);
		if(bindings == null)
		{
			return;
		}
		for(InputBinding binding : bindings.getOrDefault(key, Collections.emptySet()))
		{
			binding.setPressed(pressed);
		}
	}
}
