extends Node


@onready var countdown: Label = $MenuDisplay/countdown


func _ready():
	removeAssignedKeys()
	Gamestate.removeAllPlayers()
	$Timer.stop()

func assignKeys():
	var i=0
	for playerkey in Gamestate.getPlayerkeys():
		InputMap.add_action(Gamestate.userinput_prefix+str(i))
		var ev = InputEventKey.new()
		ev.keycode=playerkey
		InputMap.action_add_event(Gamestate.userinput_prefix+str(i), ev)
		i+=1
		
func removeAssignedKeys():
	for action in InputMap.get_actions():
		if action.get_basename().begins_with(Gamestate.userinput_prefix):
			print("Removed Action "+str(action.get_basename()))
			InputMap.erase_action(action)
	
func _unhandled_key_input(event: InputEvent) -> void:
	if event is InputEventKey:
		if event.pressed:
			#print("Key keycode:"+str(event.keycode))
			var addedID=Gamestate.addPlayer(event.keycode)
			
			$MenuDisplay.update_playerlist(Gamestate.players)
			
			if addedID!=-1:
				if len(Gamestate.getPlayerkeys())>=1: 
					$Timer.start()
				else:
					$Timer.stop()
				



func _on_timer_timeout() -> void: #Start Game
	print("Game starting")
	get_tree().change_scene_to_file("res://scenes/game.tscn")
	$Timer.stop()
	assignKeys()
	
	
func _process(delta: float) -> void:
	if $Timer.is_stopped() or $Timer.time_left>3.5:
		$MenuDisplay.updateCountdown(-1) #do not display countdown
	else:
		$MenuDisplay.updateCountdown(round($Timer.time_left)) #update countdown time
	
	
func _input(ev):
	#if ev is InputEventKey and 
	if Input.is_action_just_pressed("ui_cancel"):
		get_tree().quit()


func _on_btn_fullscreen_toggled(toggled_on: bool) -> void:
	if toggled_on:
		DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
	else:
		DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)


func _on_rounds_selection_item_selected(index: int) -> void:
	if not $Timer.is_stopped(): #only restart
		$Timer.start()

func _on_map_container_map_changed() -> void:
	if not $Timer.is_stopped(): #only restart
		$Timer.start()
