extends Node2D

##标记位
@onready var door_open_poser: Marker2D = %DoorOpenPoser
@onready var door_close_poser: Marker2D = %DoorClosePoser
@onready var door: AnimatableBody2D = %Door

var _move_tween: Tween   # 用来管理当前 tween

##门的状态，默认为0（关闭），可以切换为1（开启）
var door_state_id: int = 0
##门移动动画结束广播，输出0为关闭，输出1为开启
signal door_move_finished(int)

##开门
func door_open() -> void:
	door_move(door_open_poser)

##关门
func door_close() -> void:
	door_move(door_close_poser)

##门的移动
func door_move(poser: Node2D, duration := 0.4) -> void:
	if not poser or not door:
		return

	# 如果上一次 tween 还在，先杀掉（非常重要）
	if _move_tween and _move_tween.is_running():
		_move_tween.kill()

	var target_pos: Vector2 = poser.global_position

	_move_tween = create_tween()
	_move_tween.set_trans(Tween.TRANS_SINE)
	_move_tween.set_ease(Tween.EASE_IN_OUT)

	_move_tween.tween_property(
		door,
		"global_position",
		target_pos,
		duration
	)
	
	##移动结束的返回信号
	_move_tween.finished.connect(
		Callable(self, "_on_door_move_finished").bind(poser)
	)

##直接重置door的位置到某个poser
func reset_door(poser: Node2D)-> void:
	if not is_node_ready():
		await ready
	
	if not poser: return
	door.global_position = poser.global_position

##直接重置door的位置到某个poser的id，id可以见上面
func reset_door_state_id(id:int = 0)-> void:
	if not is_node_ready():
		await ready
		
	if id != 0 and id != 1: return
	if door_state_id == id: return
	
	var n = door_open_poser if id == 1 else door_close_poser
	door_state_id = id
	reset_door(n)

##门开关结束的广播
func _on_door_move_finished(poser: Node2D) -> void:
	if poser == door_open_poser:
		door_move_finished.emit(1)
	
	if poser == door_close_poser:
		door_move_finished.emit(0)
