extends Node2D

@export var path2d: Path2D
@export var plateform: Node2D
@export var player_trigger: PlayerTriggerVolumn

@export var move_speed: float = 200.0        # 最大前进速度
@export var returning_speed: float = 60.0     # 加速度
@export var acceleration: float = 400.0     # 加速度

@export var reach_wait_time: float = 1.5


enum State{
	IDLE,
	READY,
	MOVING,
	REACHED,
	RETURNING
}

var _current_state: State = -1
var _path_follow: PathFollow2D
var _current_speed: float = 0

func _ready() -> void:
	if path2d:
		_path_follow = PathFollow2D.new()
		_path_follow.visible = false
		path2d.add_child(_path_follow)
	
	change_state(State.IDLE)

func change_state(state:State) -> void:
	if _current_state == state:
		return
	
	_current_state = state
	
	match state:
		State.IDLE:
			##重新进入Idle可以让重置CanTrigger
			pass
		State.READY:
			ready_to_move()
		State.MOVING:
			pass
		State.REACHED:
			wait_reach_time()
		State.RETURNING:
			pass
	

## 当平台被触发时，切换状态
func _on_trigger() -> void:
	change_state(State.READY)

func _process(delta: float) -> void:
	match _current_state:
		State.IDLE:
			_process_idle(delta)
		State.MOVING:
			_process_moving(delta)
		State.RETURNING:
			_process_returning(delta)

func _process_idle(delta:float) -> void:
	if player_trigger and player_trigger._cached_player != null:
		var p:= player_trigger._cached_player as Player 
		if p.is_in_ground_state() or p.is_in_climb_state():
			_on_trigger()

func _process_moving(delta) -> void:

	_current_speed = min(_current_speed + acceleration * delta, move_speed)
	_path_follow.progress = clampf(
		_path_follow.progress + _current_speed * delta,
		0,
		path2d.curve.get_baked_length())
	plateform.global_position = _path_follow.global_position

	if _path_follow.progress_ratio >= 1.0:
		_current_speed = 0.0
		change_state(State.REACHED)

func _process_returning(delta) -> void:
	_current_speed += acceleration * delta
	_current_speed = min(_current_speed, returning_speed)

	_path_follow.progress = clampf(
		_path_follow.progress - _current_speed * delta,
		0,
		path2d.curve.get_baked_length())
	plateform.global_position = _path_follow.global_position

	if _path_follow.progress_ratio <= 0:
		_current_speed = 0.0
		change_state(State.IDLE)

##等待状态函数
func wait_reach_time()-> void:
	var expected_state := _current_state
	
	await get_tree().create_timer(reach_wait_time).timeout
	
	if _current_state != expected_state:
		return 
	
	change_state(State.RETURNING)


func ready_to_move() -> void:
	if plateform.has_method(&"shaking"):
		plateform.shaking()
		
		await plateform.shaking_finished
	
	##在结束await之后，要额外做一判断，如果其他的函数把State又改变了，则我们直接跳过
	if _current_state != State.READY:
		return
	
	start_move()

func start_move() -> void:
	if not (plateform or path2d):
		push_error("[PathDrivePlateform]:No vaild plateform or path2d checked.")
	
		# 创建 PathFollow（只创建一次）
	if not _path_follow:
		_path_follow = PathFollow2D.new()
		path2d.add_child(_path_follow)

		# 把 platform 挂到 PathFollow 下
		plateform.reparent(_path_follow)
		plateform.position = Vector2.ZERO

	_path_follow.progress = 0.0
	_current_speed = 0.0
	change_state(State.MOVING)
