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 i in quick_trigger:
		var st := i as SceneTrigger
		if not st:
			continue
		
		var tr := st.trigger_register_conifg as SceneTriggerRegister
		if not tr:
			continue
		
		var r := tr.get_register(self)
		if not r:
			continue
		
		if not r.has_signal(tr.monitor_signal):
			continue
		
		r.connect(
			tr.monitor_signal,
			func(...args):
				_on_trigger_fired(st, args)
		)

## 当信号触发
func _on_trigger_fired(trigger: SceneTrigger, signal_args: Array) -> void:
	if not trigger.can_trigger(signal_args,self):
		return
	
	for i in trigger.trigger_effect_pairs:
		var sp := i as SceneTriggerEffectPair
		if not sp.target:
			continue
		
		var t := sp.target.get_effect_target(self)
		if not t:
			continue
		
		var exs := sp.effect
		for j in exs:
			var ex := j as SceneTriggerEffect
			ex.apply_effect(t)

## =============================
## External API
## =============================
func switch_act_with_id(id: int,trans_overwrite:int = 0) -> void:
	_act_manager.switch_act_with_id(id,trans_overwrite)

## 外部快速获取Act Manager
func get_act_manager() -> ActManager:
	return _act_manager

## 外部快速获取scene root
func get_scene_root() -> ReedScene:
	return _scene if _scene else get_parent()

## 外部快速获取获取props映射
func get_props() -> Dictionary:
	return _props
