extends Spatial

var player:Player

const MAX_ROAD_INDEX = 1
var error_rate:float = 0.00
var underspeed_rate:float = 0.00


func _ready():
	randomize()


func _physics_process(delta):
	if is_network_master() && player != null:
		if player.is_out:
			if player.is_resetable:
				player.reset()
		else:
			if player.get_road() != null:
				var rate = randf()
				var road = player.get_road()
				var road_index = 0
				var speed_constrain = 0.0
				while road != null && road_index < MAX_ROAD_INDEX:
					for index in range(road.speed_constrains.size()):
						var constrain = road.speed_constrains[index]
						if constrain.z > 0:
							speed_constrain = max(speed_constrain, constrain.z)
						elif constrain.z < 0:
							speed_constrain = min(speed_constrain, constrain.z)
					road = player.route.get_road(road.get_index() + 1)
					road_index += 1
					
				var speed = player.current_speed
				if speed_constrain < 0:
					player.thrust = 1
				elif speed_constrain > 0 && speed > speed_constrain:
					player.thrust = -1
				elif rate > underspeed_rate:
						player.thrust = 1
				else:
					player.thrust = 0


func set_player(path:String):
	player = get_node(path)
	get_node("inventory").set_player(player)


func set_error_rate(new_error_rate:float):
	error_rate = new_error_rate


func set_underspeed_rate(new_underspeed_rate:float):
	underspeed_rate = new_underspeed_rate
