class_name SceneManager
extends Node

@export var quick_trigger: Array[SceneTrigger]
## ==============================
## References
## ==============================
var _scene: ReedScene
var _act_manager: ActManager
var _props: Dictionary # prop_id -> PropComponent

func _ready() -> void:
	await get_parent().ready
	
	_resolve_scene()
	if _scene == null:
		push_error("[SceneManager] Parent is not ReedScene.")
		return

	_resolve_references()
	
	_bind_quick_trigger()

func _resolve_scene() -> void:
	var p := get_parent()
	if p is ReedScene:
		_scene = p
	else:
		_scene = null

func _resolve_references() -> void:
	_act_manager = _scene._act_manager
	_props = _scene._prop_map

func _bind_quick_trigger() -> void:
	for qt in quick_trigger:
		if qt is PropIDSceneTrigger:
			_bind_prop_id_trigger(qt)
		elif qt is NodePathSceneTrigger:
			_bind_node_path_trigger(qt)

## 通过Prop id来绑定signal
func _bind_prop_id_trigger(trigger: PropIDSceneTrigger) -> void:
	var prop : Node = _props.get(trigger.prop_id).get_parent()
	if prop == null:
		return

	var s: StringName = trigger.monitor_signal
	if not prop.has_signal(s):
		push_error("Prop has no signal: %s" % trigger.monitor_signal)
		return

	prop.connect(
		trigger.monitor_signal,
		func(...args):
			_on_trigger_fired(trigger, args)
	)

## 通过NodePath来绑定signal
func _bind_node_path_trigger(trigger: NodePathSceneTrigger) -> void:
	if trigger.path.is_empty():
		return
	
	var n : Node = self.get_node_or_null(trigger.path)
	
	if n == null:
		return

	var s: StringName = trigger.monitor_signal
	if not n.has_signal(s):
		push_error("Prop has no signal: %s" % trigger.monitor_signal)
		return

	n.connect(
		trigger.monitor_signal,
		func(...args):
			_on_trigger_fired(trigger, args)
	)

## 当信号触发
func _on_trigger_fired(trigger: SceneTrigger, signal_args: Array) -> void:
	if not trigger.can_trigger(signal_args):
		return

	var target_act_id: int = trigger.target_act_id
	var trans_overwrite:  int = trigger.trans_overwrite
	
	if target_act_id < 0:
		return
	
	_act_manager.switch_act_with_id(target_act_id,trans_overwrite)
	
