extends Node


#var playerkeys: Array[int] = []
var players: Array[Player] = []
var last_players: Array[Player] = []

var userinput_prefix="inputP"

var time_elapsed=0

var map_scene_name=""
var map_scene_name_prefix="res://scenes/map_"
var map_scene_name_postfix=".tscn"

var rounds=3

func getRounds():
	return rounds
	
func setRounds(r):
	print("Rounds set to "+str(r))
	rounds=r
	
func getSelectedMap(): #return only short map name "00"
	return map_scene_name
	
func getSelectedMapSceneName(): #returns full scene path "res://scenes/map_00.tscn"
	return map_scene_name_prefix+map_scene_name+map_scene_name_postfix
	
func setSelectedMap(mapname):
	map_scene_name=mapname

func checkColoriFree(i):
	var free=true
	for p in players:
		if p.colori==i: #already taken
			free=false
	return free
	

func addPlayer(key:int):
	#return -1 if player already exists with this key. else return id of player added
	if not getPlayerkeys().has(key): #key is not yet registered
		var prefered_colori=0
		for p in last_players:
			if p.inputkey==key: #key was used in last round
				prefered_colori=p.colori
		
		#check if color is free, else assign next free
		while not checkColoriFree(prefered_colori):
			prefered_colori+=1
		
		players.append(Player.new(key,prefered_colori))

		return prefered_colori
	else:
		return -1
		
func removeAllPlayers():
	last_players=players
	players=[]


func getPlayerkeys() -> Array[int]:
	var playerkeys: Array[int] = []
	for player in players:
		playerkeys.append(player.inputkey)
	return playerkeys

	
func getPlayers() -> Array[Player]:
	return players

class Player:
	var inputkey:int
	var color:Color
	var colori
	
	func _init(key:int, pcolori:int=-1):
		inputkey=key
		colori=pcolori
		var sat = 1.0
		var val = 1.0 #1 is medium gray
		
		if colori<0:
			color=Color.from_hsv(randf_range(0.0,1.0), sat,val,1.0)
		else:
			color=Color.from_hsv(fmod(0.3*colori,1.0), sat,val,1.0)
		
	
func startGame():
	for player in players:
		player.setRunning(true)
	
func addTimeElapsed(delta):
	time_elapsed+=delta
	
func getTimeElapsed():
	return time_elapsed

func resetTimeElapsed():
	time_elapsed=0
