extends Camera3D

@onready var playerSelectButton = preload("res://scenes/camera/UI/playerSelectionButton.tscn")

@onready var roundLabel = $CanvasLayer/Control/General/roundLabel
@onready var playerNameLabel = $CanvasLayer/Control/Player/PlayerNameLabel
@onready var itemCards = $CanvasLayer/Control/Player/ItemCards
@onready var magazineLabel = $CanvasLayer/Control/Player/MagazineLabel
@onready var playerSelection = $CanvasLayer/Control/Player/PlayerSelection

#@onready var itemStandardBulletButton = $
var currentPlayer: Player
var selectablePlayers: Array[Player]

signal itemSelected(_itemType: GLOBALS.ITEMTYPES)
signal nextTurn()


func _ready() -> void:
	for i in itemCards.get_children():
		if i.has_signal("selected"):
			i.selected.connect(selectItem.bind())

func setRound(_round: int) -> void:
	roundLabel.text = str(_round)

func updatePlayerStats():
	playerNameLabel.text = str(currentPlayer.getGameName())
	magazineLabel.text = str(currentPlayer.gun.magazineSize) + "/" + str(currentPlayer.gun.getBulletAmount())
	updatePlayerSelection()
	updateItemCards()

func setCurrentPlayer(_currentPlayer: Player):
	currentPlayer = _currentPlayer
	updatePlayerStats()

func selectItem(_itemType: GLOBALS.ITEMTYPES):
	print(currentPlayer.gun.magazineSizeLeft())
	if currentPlayer.gun.magazineSizeLeft() > 0:
		itemSelected.emit(_itemType)

func updateItemCards() -> void:
	if currentPlayer.gun.magazineSizeLeft() <= 0:
		for i in itemCards.get_children():
			if i.has_node("ItemButton"):
				i.itemButton.disabled = true
	else:
		for i in itemCards.get_children():
			if i.has_node("ItemButton"):
				i.itemButton.disabled = false
	for i in GLOBALS.ITEMTYPES:
		var counter = 0
		for j in currentPlayer.getItems():
			if j.type == GLOBALS.ITEMTYPES[i]:
				counter += 1
		for j in itemCards.get_children():
			if j.has_node("ItemButton/ItemAmountLabel") and j.itemType == GLOBALS.ITEMTYPES[i]:
				j.setAmount(counter)
				if counter <= 0:
					j.visible = false
				else: 
					j.visible = true


func updatePlayerSelection() -> void:
	for i in playerSelection.get_children():
		i.free()
	var newButtonGroup = ButtonGroup.new()
	for i in selectablePlayers:
		if i != currentPlayer:
			var newSelection = playerSelectButton.instantiate()
			newSelection.setPlayer(i)
			newSelection.button_group = newButtonGroup
			playerSelection.add_child(newSelection)

	playerSelection.get_child(0).button_pressed = true
	var newSelection = playerSelectButton.instantiate()
	newSelection.setPlayer(currentPlayer)
	newSelection.button_group = newButtonGroup
	playerSelection.add_child(newSelection)

	
	
func _on_next_turn_button_pressed() -> void:
	currentPlayer.selectPlayer(getPlayerSelection())
	nextTurn.emit()


func getPlayerSelection() -> Player:
	for i in playerSelection.get_children():
		if i.button_pressed == true:
			return i.player
	return currentPlayer
