extends Node

# 全局事件系统 - 提供解耦的事件通信机制
# 允许不同模块之间通过事件进行通信，避免直接依赖

# 事件监听器存储
var event_listeners: Dictionary = {}

func _ready():
	print("EventSystem 初始化完成")

# 注册事件监听器
func connect_event(event_name: String, callback: Callable, target: Node = null):
	if not event_listeners.has(event_name):
		event_listeners[event_name] = []
	
	var listener_info = {
		"callback": callback,
		"target": target
	}
	
	event_listeners[event_name].append(listener_info)
	print("注册事件监听器: ", event_name, " -> ", callback)

# 移除事件监听器
func disconnect_event(event_name: String, callback: Callable, target: Node = null):
	if not event_listeners.has(event_name):
		return
	
	var listeners = event_listeners[event_name]
	for i in range(listeners.size() - 1, -1, -1):
		var listener = listeners[i]
		if listener.callback == callback and listener.target == target:
			listeners.remove_at(i)
			print("移除事件监听器: ", event_name, " -> ", callback)
			break

# 发送事件
func emit_event(event_name: String, data: Variant = null):
	print("发送事件: ", event_name, " 数据: ", data)
	
	if not event_listeners.has(event_name):
		return
	
	var listeners = event_listeners[event_name]
	for listener_info in listeners:
		var target = listener_info.target
		var callback = listener_info.callback
		
		# 检查目标节点是否仍然有效
		if target != null and not is_instance_valid(target):
			continue
		
		# 调用回调函数
		if data != null:
			callback.call(data)
		else:
			callback.call()

# 清理无效的监听器
func cleanup_invalid_listeners():
	for event_name in event_listeners.keys():
		var listeners = event_listeners[event_name]
		for i in range(listeners.size() - 1, -1, -1):
			var listener = listeners[i]
			var target = listener.target
			if target != null and not is_instance_valid(target):
				listeners.remove_at(i)
				print("清理无效监听器: ", event_name)

# 获取事件监听器数量
func get_listener_count(event_name: String) -> int:
	if not event_listeners.has(event_name):
		return 0
	return event_listeners[event_name].size()

# 清空所有事件监听器
func clear_all_listeners():
	event_listeners.clear()
	print("清空所有事件监听器")
