extends Node2D

onready var buttonPlayer = $"%ButtonPlayer"
onready var activatorArea = $"%ActivatorArea"
onready var signal_manager := get_tree().root.get_child(4).get_node("%SignalManager")
onready var unactivatable_timer := $Timer
onready var get_back_timer := $GetBackTimer

export var elevator_time := 30
var activatable = false

func _ready() -> void:
	get_back_timer.wait_time = elevator_time
	$Label.text = String(elevator_time)
	signal_manager.connect("remaining_time_changed", self, "update_label")

func update_label(remaining_time: float) -> void:
	$Label.text = String(round(remaining_time))

func _input(event: InputEvent) -> void:
	if activatable && Input.is_action_just_released("interact"):
		selfActivate()
		signal_manager.emit_signal("terminal_activated", elevator_time)
		get_back_timer.start()


func selfActivate():
	buttonPlayer.play("pushing")
	#TODO dis importante
	activatorArea.set_deferred("monitoring", false)
	$GetBackMusic.play()


func _on_ActivatorArea_area_entered(area:Area2D) -> void:
		$Highlight.visible = true
		activatable = true

func _on_ActivatorArea_area_exited(area:Area2D) -> void:
		unactivatable_timer.start()

func _on_Timer_timeout() -> void:
	for body in activatorArea.get_overlapping_bodies():
		if body.is_in_group("player"):
			return
	$Highlight.visible = false
	activatable = false


func _on_GetBackTimer_timeout() -> void:
	signal_manager.emit_signal("getback_timer_up")
