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")
	if is_network_master():
		route.rpc("add_road",roads_factory.START, -1)


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


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.rpc("add_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