extends Control
class_name UIComponent

var update_interval : float = 1
var last_update : float = 0

@onready var nectar_bar : ProgressBar = get_node("%NectarBar")
@onready var help_text_container : VBoxContainer = get_node("%HelpTextContainer")
@onready var help_text_items : Array[Node] = help_text_container.get_children()
@onready var level_text_label : Label = get_node("%LevelText")
@onready var level_timer_label : Label = get_node("%LevelTimer")
@onready var par_text_label : Label = get_node("%ParText")
@onready var bee_counter : Label = get_node("%BeeCounter")


var disable_pause : bool = false

func _ready() -> void:
	hide_help_text()
	update_ui()
	%PauseMenu.hide()
	%PauseMenu.connect("resume_game", Callable(self, "unpause_game"))

	%QuitButton.connect("pressed", Callable(self, "quit_game"))
	%ResumeButton.connect("pressed", Callable(self, "unpause_game"))

	bee_counter.hide()

func _process(delta : float) -> void:
	last_update += delta

	disable_pause = false # This is a mega hacky way to stop the game instantly repausing after unpausing

	if last_update > update_interval:
		last_update = 0
		update_ui()

	if GameState.level_complete:
		update_ui()

	level_timer_label.text = Str.seconds_to_hms(GameState.level_timer)

func _unhandled_input(event : InputEvent) -> void:
	if event.is_action_pressed("ui_cancel"):
			Log.pr("UIComponent: ui_cancel pressed")
			if get_tree().paused == false && disable_pause == false:
				Log.pr("Game is not paused, so pausing it...")
				pause_game()

func update_ui() -> void:
	nectar_bar.value = GameState.gathered_nectar
	nectar_bar.max_value = GameState.required_nectar

	bee_counter.text = "Bees: " + str(GameState.bees_available - GameState.dead_bees) + "/" + str(GameState.bees_available)
	bee_counter.show()
	
func hide_help_text() -> void:
	for item : Node in help_text_items:
		item.hide()

func show_help_text(label: String) -> void:
	hide_help_text()
	for item : Node in help_text_items:
		if item.name == label:
			item.show()

func update_level_text(text: String) -> void:
	level_text_label.text = text

func update_par_text(text: String) -> void:
	par_text_label.text = text

func quit_game() -> void:
	get_tree().paused = false
	GameState.reset()
	SceneMgr.load_scene("MAINMENU")

func pause_game() -> void:
	get_tree().paused = true
	%PauseMenu.show()

func unpause_game() -> void:
	Log.pr("Pause Menu: Close button pressed")
	disable_pause = true
	%PauseMenu.hide()
	get_tree().paused = false

