extends LimboHSM

@onready var root: Normal = %Normal

##自动跳跃逻辑
@export var auto_jump_cached_time: float = .2
var auto_jump_timer: float

func _setup() -> void:
#region Jump and fall
	#Jump State -> Fall State
	self.add_transition(root.jump_state,root.fall_state,root.jump_state.EVENT_FINISHED)
	#Fall State -> Jump State
	self.add_transition(root.fall_state,root.jump_state,&"air_to_jump")
#endregion
	
#region Wall jump
	#ANYSTATE -> Wall Jump State
	self.add_transition(ANYSTATE,root.wall_jump_state,&"wall_jump")
	#Wall Jump State -> Fall State
	self.add_transition(root.wall_jump_state,root.fall_state,root.wall_jump_state.EVENT_FINISHED)
#endregion
	
	self.add_event_handler(&"trigger_jump",_handler_trigger_jump)

func _enter() -> void:
	
	## 进入时，只要want to jump == true，则会触发跳跃而不是fall
	var want_to_jump = blackboard.get_var(&"want_to_jump",false)
	
	initial_state = root.fall_state
	if want_to_jump:
		initial_state = root.jump_state
	
	self.blackboard.set_var(&"want_to_jump",false)


func _update(delta: float) -> void:
	if auto_jump_timer > 0:
		auto_jump_timer -= delta
		print("允许自动跳")
	
	if agent.get_is_on_floor() && agent.velocity.y >= 0:
		#自动跳
		if auto_jump_timer > 0:
			auto_jump_timer = 0
			self.blackboard.set_var(&"want_to_jump",true)
			change_active_state(root.jump_state)
		
		get_root().dispatch(self.EVENT_FINISHED)

func _cache_auto_jump_timer() -> void:
	auto_jump_timer = auto_jump_cached_time

#region 输入绑定事件
func _handler_trigger_jump() -> bool:
	if agent.is_on_wall_only():
		get_root().dispatch(&"wall_jump")
	
	_cache_auto_jump_timer()
	return true
#endregion
