extends CanvasLayer

var _in_play := false

func _ready():
	process_mode = Node.PROCESS_MODE_ALWAYS
	visible = false
	EventBus.game_started.connect(func(): _in_play = true)
	EventBus.game_won.connect(func(): _in_play = false)
	EventBus.game_lost.connect(func(_reason: String): _in_play = false)
	$Center/Card/Margin/Column/ResumeButton.pressed.connect(_on_resume_pressed)
	$Center/Card/Margin/Column/RestartButton.pressed.connect(_on_restart_pressed)

func _unhandled_input(event):
	if not _in_play:
		return
	if event is InputEventKey and event.pressed and not event.echo and event.keycode == KEY_ESCAPE:
		_toggle()
		get_viewport().set_input_as_handled()
		return
	if get_tree().paused and event is InputEventKey and event.pressed and not event.echo and event.keycode == KEY_SPACE:
		_on_resume_pressed()
		get_viewport().set_input_as_handled()

func _toggle():
	var paused := not get_tree().paused
	get_tree().paused = paused
	visible = paused

func _on_resume_pressed():
	get_tree().paused = false
	visible = false

func _on_restart_pressed():
	get_tree().paused = false
	get_tree().reload_current_scene()
