extends Spatial

class_name Game

var players:Array
var route:Route
var first:Player
var last:Player

const REMOVE_LAST = 2


func _ready():
	route = get_node("route")
	find_node("sun").set_visible(config.get_value("graphics","light", false))
	if find_node("sun").is_visible_in_tree():
		find_node("sun").set_shadow(config.get_value("graphics","shadows", false))
	if is_network_master():
		route.set_road(roads_factory.START, -1)
		route.rpc("set_road",roads_factory.START, -1)


func _physics_process(delta):
	if is_network_master():
		set_player_order()
		check_autotrack()


func get_player(player_id:String):
	if get_node("players") != null && get_node("players").has_node(player_id):
		return get_node("players").get_node(player_id)
	return null


func get_player_by_network_id(network_id:int):
	return get_player(str(network_id))


func set_player_order():
	players = get_node("players").get_children()
	players.sort_custom(PlayerSorter,"sort")
	if players.size() > 0 && players[0] != first:
		new_first(players[0])
	if players.size() > 0 && players[players.size()-1] != last:
		last = players[players.size()-1]


func new_first(player):
	if first != null:
		first.rpc("set_first",false)
	first = player
	first.rpc("set_first",true)


func check_autotrack():
	if first != null:
		if first.position.x != -1 && route.get_last_road() != null:
			if first.position.x == route.get_last_road().get_index():
				route.set_road(roads_factory.STRAIGHT, -1)
				route.rpc("set_road", roads_factory.STRAIGHT, -1)


class PlayerSorter:
	static func sort(a, b):
		return a.position.x > b.position.x || a.position.x == b.position.x && a.position.y > b.position.y