extends Node3D

const DOOR_OPEN_X := 1.154
const DOOR_CLOSED_X := 0.7
const DOOR_DEFAULT_TIME := 3.0
const DOOR_FAST_CLOSE_TIME := 1.0
const DOOR_REOPEN_TIME := 0.4

var _tween: Tween = null

func _ready():
	$ElevatorDoorRight.position = Vector3(DOOR_CLOSED_X, 0, 0)
	$ElevatorDoorLeft.position = Vector3(-DOOR_CLOSED_X, 0, 0)
	_set_door_collision(true)
	EventBus.doors_opened.connect(_on_doors_opened)
	EventBus.doors_closed.connect(_on_doors_closed)
	EventBus.pulse_started.connect(_on_pulse_started)
	EventBus.pulse_blocked.connect(_on_pulse_blocked)

func _on_doors_opened():
	_set_door_collision(false)
	_tween_doors(DOOR_OPEN_X, DOOR_DEFAULT_TIME)

func _on_doors_closed(fast: bool):
	_set_door_collision(true)
	_tween_doors(DOOR_CLOSED_X, DOOR_FAST_CLOSE_TIME if fast else DOOR_DEFAULT_TIME)
	_tween.chain().tween_callback(func(): EventBus.doors_fully_closed.emit())

func _on_pulse_started(duration: float):
	_set_door_collision(true)
	_tween_doors(DOOR_CLOSED_X, duration)

func _on_pulse_blocked():
	_set_door_collision(false)
	_tween_doors(DOOR_OPEN_X, DOOR_REOPEN_TIME)

func _set_door_collision(enabled: bool):
	$ElevatorDoorRight/CollisionShape3D.disabled = not enabled
	$ElevatorDoorLeft/CollisionShape3D.disabled = not enabled

func get_door_close_progress() -> float:
	var cur: float = $ElevatorDoorRight.position.x
	return clamp((DOOR_OPEN_X - cur) / (DOOR_OPEN_X - DOOR_CLOSED_X), 0.0, 1.0)

func _tween_doors(target_x: float, duration: float):
	if _tween:
		_tween.kill()
	_tween = create_tween()
	_tween.set_parallel(true)
	_tween.tween_property($ElevatorDoorRight, "position:x", target_x, duration)
	_tween.tween_property($ElevatorDoorLeft, "position:x", -target_x, duration)
