extends Node3D

@onready var characterScene = preload("res://scenes/character/character.tscn")

@onready var camera = $cameraRottion/Camera3D
@onready var charactersContainer = $CharactersContainer

var players: Array[Player]
var selectablePlayers: Array[Player] = players.duplicate()
var guns: Array[Gun]
var roundCount: int = 0
var playerCount: int = 2
var lastCharacterRotation: int = 0
var rotationInterval: float = 360 / playerCount
var currentPlayer: Player
var currentPlayerIndex: int = 0

func _ready() -> void:
	camera.itemSelected.connect(selectItem.bind())
	camera.nextTurn.connect(nextTurn.bind())
	addNewPlayer("Test 1")
	addNewPlayer("Test 2")
	players[1].bot = true
	players[0].addItem(StandardBullet.new())
	players[0].addItem(LuckyBullet.new())
	nextRound()
	nextTurn()

func nextTurn():
	if currentPlayerIndex + 1 > selectablePlayers.size():
		print("Shoot")
		currentPlayerIndex = 0
		givePlayersRandomGun()
		shootPlayers()
	else:
		currentPlayer = selectablePlayers[currentPlayerIndex]
		currentPlayerIndex += 1
		#if not currentPlayer.bot:
		camera.setCurrentPlayer(currentPlayer)

func addNewPlayer(_name: String):
	var newGun = Gun.new()
	guns.append(newGun)
	var newCharacter = addCharacter()
	var newPlayer = Player.new(_name, newGun, newCharacter)
	players.append(newPlayer)
	selectablePlayers.append(newPlayer)
	camera.selectablePlayers = selectablePlayers
	newPlayer.dead.connect(playerDied.bind())

func addCharacter() -> Character:
	var newCharacter = characterScene.instantiate()
	charactersContainer.add_child(newCharacter)
	lastCharacterRotation += rotationInterval
	newCharacter.rotation_degrees.y += lastCharacterRotation
	return newCharacter


func playerDied(_player: Player) -> void:
	selectablePlayers.erase(_player)
	camera.selectablePlayers = selectablePlayers
	print("Player " + _player.getGameName() + " is dead")

func givePlayersRandomGun():
	randomize()
	var gunPool = guns.duplicate()
	for i in guns.size():
		var newGun = gunPool.pick_random()
		selectablePlayers[i].giveGun(newGun)
		gunPool.erase(newGun)

func givePlayersGun():
	for i in guns:
		i.mainOwner.giveGun(i)
		i.mainOwner.gun.resetMagazine()

func nextRound() -> void:
	givePlayersGun()
	for i in players:
		i.addItem(StandardBullet.new())
	roundCount += 1
	camera.setRound(roundCount)
	currentPlayerIndex = 0

func shootPlayers():
	for i in selectablePlayers:
		i.shootAtSelectedPlayer()
	nextRound()
	nextTurn()

func selectItem(_itemType: GLOBALS.ITEMTYPES):
	playerUseItemType(currentPlayer, _itemType)
	print(_itemType)

func playerUseItemType(_player: Player, _type: GLOBALS.ITEMTYPES) -> void:
	for i in currentPlayer.getItems():
		if i.type == _type:
			currentPlayer.useItem(i)
			break
	camera.updatePlayerStats()
