extends LimboHSM

@onready var root: Normal = %Normal

func _setup() -> void:
	self.add_event_handler(&"trigger_jump",_handler_trigger_jump)
	self.add_event_handler(root.climb_state.EVENT_FINISHED,_handler_climb_state_finished)
	self.add_event_handler(root.climb_jump_state.EVENT_FINISHED,_handler_climb_state_finished)
	
	self.add_transition(root.climb_state,root.climb_jump_state,&"want_to_climb_jump")

func _enter() -> void:
	if agent.is_on_wall():##如果已经在Wall上，则什么都不做
		return
	
	snap_to_wall()

func snap_to_wall(max_snap_dist := 6.0) -> bool:
	var wall_dir : float = sign(agent.wall_detector.wall_direction.x)
	
	var from : Vector2 = agent.global_position
	var to : Vector2 = from + Vector2(wall_dir * max_snap_dist, 0)
	
	var query := PhysicsRayQueryParameters2D.create(from, to)
	query.exclude = [agent]
	query.collision_mask = agent.collision_mask
	
	var result = agent.get_world_2d().direct_space_state.intersect_ray(query)
	if result:
		var target_x = result.position.x - wall_dir * agent.wall_snap_offset
		agent.global_position.x = target_x
		return true
	
	return false

func _handler_climb_state_finished() -> bool:
	if agent.is_on_floor():
		self.dispatch(&"exit_on_ground")
	else:
		self.dispatch(&"exit_on_air")
	
	return true

func _handler_trigger_jump() -> bool:
	if self.get_active_state() == root.climb_state:
		var input_x: float = agent.m_input_intent_direction.x
		var wall_dir: float = agent.get_wall_normal().x
		if sign(input_x) * sign(wall_dir) > 0:
			root._trigger_climb_cd(.12)
			self.get_root().blackboard.set_var(&"want_to_jump",true)
			_handler_climb_state_finished()
			return true
		
		self.dispatch(&"want_to_climb_jump")
	return true
