extends Node3D

const MESSAGE_FMT := (
	"-=  H E L L O   G R U N K E R  =-\n"
	+ "Your GRUNK QUOTA today:\n"
	+ ".... {0} g\n"
	+ "GRUNK collected:\n"
	+ ".... {1} g\n"
	+ "-================================-\n"
	+ "{2}\n"
	+ "{3}\n"
	+ "Look forward to: {4}\n"
	+ ".... at {5} g\n"
	+ "-= YOUR BENEFACTORS THANK YOU =-"
)

const STALLING_MSG := "\n\n\n\n\n. . . C a l c u l a t i n G . . ."

@onready var text_terminal: TextTerminal = %TextTerminal
@onready var stall_timer: Timer = %StallTimer
@onready var terminal_animation: AnimationPlayer = %TerminalAnimation


func _ready() -> void:
	Game.manager.grunk_emptied.connect(_on_tank_emptied)
	recompute()


func _next_milestone_name() -> String:
	var next_milestone := Game.manager.next_milestone()
	return next_milestone.name if next_milestone else "NOTHING"


func _next_milestone_amount() -> String:
	var next_milestone_amt := Game.manager.next_milestone_amount()
	return str(next_milestone_amt) if next_milestone_amt >= 0 else "NEVER"


func build_message() -> String:
	var msg_lines := Game.manager.latest_milestone().message.split("\n")
	var line_1 := msg_lines[0]
	var line_2 := msg_lines[1] if len(msg_lines) >= 2 else ""
	return MESSAGE_FMT.format(
		[
			int(Game.manager.grunk_quota),
			int(Game.manager.grunk_vault),
			line_1,
			line_2,
			_next_milestone_name(),
			_next_milestone_amount()
		]
	)


## Trigger a recompute.
##
## Under the hood this is instantaneous, but we want to stall for dramatic effect.
func recompute() -> void:
	text_terminal.text = STALLING_MSG
	terminal_animation.play("jangle")
	stall_timer.start()


func _update_terminal() -> void:
	text_terminal.text = build_message()


func _on_tank_emptied(_amount: float) -> void:
	recompute()
