extends Control

@export var world_path : NodePath = NodePath()

@onready var game_running_widgets : Control = $'GameRunningWidgets'
@onready var game_startup_widgets : Control = $'GameStartupWidgets'
@onready var game_finished_widgets : Control = $'GameFinishedWidgets'
@onready var game_level_select_widgets : Control = $'GameLevelSelectWidgets'

@onready var level_list_container: HBoxContainer = $'GameLevelSelectWidgets/LevelListContainer'

@onready var player1_score_label : Label = $'GameRunningWidgets/Player1Widgets/ScoreLabel'
@onready var player1_energy_progressbar : ProgressBar = $'GameRunningWidgets/Player1Widgets/EnergyProgressBar'
@onready var player2_score_label : Label = $'GameRunningWidgets/Player2Widgets/ScoreLabel'
@onready var player2_energy_progressbar : ProgressBar = $'GameRunningWidgets/Player2Widgets/EnergyProgressBar'
@onready var player2_widgets : Control = $'GameRunningWidgets/Player2Widgets'

@onready var time_left_label : Label = $'GameRunningWidgets/TimeWidgets/TimeLeftLabel'

@onready var winner_label : Label = $'GameFinishedWidgets/VBoxContainer/WinnerLabel'
@onready var player1_stats_points : Label = $'GameFinishedWidgets/VBoxContainer/HBoxContainer/Player1Stats/Points'
@onready var player2_stats_points : Label = $'GameFinishedWidgets/VBoxContainer/HBoxContainer/Player2Stats/Points'

var world : World = null

# Called when the node enters the scene tree for the first time.
func _ready():
	world = get_node(world_path)

	initialize_level_buttons()
	
	game_level_select_widgets.connect("visibility_changed", on_game_level_select_visibility_changed)
	
	if world.players.size() == 1:
		player2_widgets.visible = false

func _process(_delta):
	if world.game_state == World.GameState.Startup:
		game_startup_widgets.visible = true
		game_running_widgets.visible = false
		game_finished_widgets.visible = false
		game_level_select_widgets.visible = false
	elif world.game_state == World.GameState.LevelSelect:
		game_startup_widgets.visible = false
		game_running_widgets.visible = false
		game_finished_widgets.visible = false
		game_level_select_widgets.visible = true
	elif world.game_state == World.GameState.Running:
		game_startup_widgets.visible = false
		game_running_widgets.visible = true
		game_finished_widgets.visible = false
		game_level_select_widgets.visible = false		
		
		var minutes = floor(world.time_left / 60.)
		var seconds = fmod(floor(world.time_left), 60)
		var milliseconds = floor((world.time_left - floor(world.time_left)) * 100)
		
		time_left_label.text = "%02d:%02d:%02d" % [minutes, seconds, milliseconds]
		
		player1_score_label.add_theme_color_override("font-color", world.players[0].color)
		if player2_widgets.visible:
			player2_score_label.add_theme_color_override("font-color", world.players[1].color)
	elif world.game_state == World.GameState.Finished:
		game_startup_widgets.visible = false
		game_running_widgets.visible = false
		game_finished_widgets.visible = true
		game_level_select_widgets.visible = false		
	
	player1_score_label.text = str(world.players[0].score)
	player1_energy_progressbar.value = world.players[0].energy
	player1_stats_points.text = str(world.players[0].score)
	var winner_player : Player = world.players[0]
	
	if player2_widgets.visible:
		player2_score_label.text = str(world.players[1].score)
		player2_energy_progressbar.value = world.players[1].energy
		player2_stats_points.text = str(world.players[1].score)
		if world.players[1].score > world.players[0].score:
			winner_player = world.players[1]

	winner_label.add_theme_color_override("font_color", winner_player.color)
	winner_label.text = winner_player.name + " wins!"
	

func _input(event):
	if event.is_action_pressed("ui_accept"):
		if world.game_state == World.GameState.Startup:
			world.game_state = World.GameState.LevelSelect
	if event.is_action_pressed("ui_menu"):			
		if world.game_state == World.GameState.Finished:
			world.game_state = World.GameState.Startup
	if event.is_action_pressed("ui_cancel"):
		if world.game_state == World.GameState.LevelSelect:
			world.game_state = World.GameState.Startup
		elif world.game_state == World.GameState.Startup:
			get_tree().quit()

func initialize_level_buttons():
	var level_button : Button = level_list_container.get_child(0)
	if level_button == null:
		push_error("Cannot initialize level selection: no level button found!")
		return

	var level_select_button_group : ButtonGroup = level_button.button_group
	level_select_button_group.connect("pressed", on_level_button_pressed)
	
func update_selected_level():
	var level_button: Button = level_list_container.get_child(0)
	if level_button == null:
		push_error("Cannot update selected level: no level found")
	
	var button_index: int = -1
	for button: Button in level_button.button_group.get_buttons():
		button_index += 1
		if button_index == world.level_index:
			button.grab_focus()
			return

func on_level_button_pressed(button: Button):
	print("level button " + str(button) + " pressed")
	var button_index: int = -1
	for level_button : Button in level_list_container.get_children():
		button_index += 1
		print(str(level_button) + " toggled: " + str(level_button.is_hovered()))
		if level_button == button:
			world.level_index = button_index
	
	print("level index: " + str(world.level_index))
	world.game_state = World.GameState.Running

func on_game_level_select_visibility_changed():
	update_selected_level()
