@icon("res://components/Triggerer/radio.svg")
extends Base
## A trigger object to trigger things and read in triggers
##
## An object used for other objects to connect to for triggers.
## Objects can call the read function with a callback function to
## read in future triggers of a key to that callback. Objects can
## then call the trigger function to trigger everything listening
## to a key.

var _connections = {}


## Trigger an event to be read in by other objects
func trigger(key: String, data: Dictionary = {}) -> void:
	_info("Triggered key ∧%s∧" % [key])
	
	data.trigger = key
	
	if _connections.has(key):
		_connections[key] = _connections[key].filter(func(x): return x.is_valid())
		
		for callback in _connections[key]:
			callback.call(data)
	
	if _connections.has("any"):
		_connections["any"] = _connections["any"].filter(func(x): return x.is_valid())
		
		for callback in _connections["any"]:
			callback.call(data)


## Read in future triggers of a key to a callback
func listen(key: String, callback: Callable) -> void:
	if not _connections.has(key):
		_info("Created new connection key ∧%s∧" % [key])
		_connections[key] = []
	
	_info("Callback ∨%s∨ on →%s← added to key ∧%s∧" % [callback.get_method(), callback.get_object().name, key])
	_connections[key].push_back(callback)