extends Spatial

class_name BotPlayer

var player:Player

const MAX_OFFSET = 8.0
const OFFSET_STEPS = 0.1
const PRE_BREAK_DISTANCE = 3.0

var break_constrain = 0.0
var break_distance = 0.0
var thrust_distance = 0.0

export var difficulty:float = 0.0
var rate = 0.0


func _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 road = player.get_road()
				var speed = player.current_speed
				var offset = 0
				var distance = player.follow.get_offset() - OFFSET_STEPS
				var tmp_constrain = 0.0

				break_constrain = 0.0
				break_distance = 0.0
				thrust_distance = 0.0

				while offset <= MAX_OFFSET && road != null:
					var constrain_index = road.get_constrain_index(distance)
					var road_length = road.get_lane_curve(player.lane).get_baked_length()
					if constrain_index >= 0:
						tmp_constrain = road.speed_constrains[constrain_index].z
						if tmp_constrain > 0 && (break_constrain == 0.0 || tmp_constrain < break_constrain):
							break_constrain = tmp_constrain
							if break_distance == 0:
								break_distance = offset
						if tmp_constrain < 0 && thrust_distance == 0:
							thrust_distance = offset

					distance += OFFSET_STEPS
					offset += OFFSET_STEPS

					if distance >= road_length && gamestate.game != null:
						distance = 0
						road = gamestate.game.route.get_road(road.get_index()+1)

				if break_constrain > 0 && speed > break_constrain - 0.005 && break_distance < thrust_distance + PRE_BREAK_DISTANCE && rate < difficulty:
					player.thrust = -1
				elif speed - 0.01 < break_constrain:
					player.thrust = 1
				elif break_constrain == 0.0 && rate < difficulty || speed < 0.02:
					player.thrust = 1
				else:
					player.thrust = 0


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


func set_difficulty(new_difficulty:float):
	difficulty = new_difficulty


func _on_rate_timer_timeout():
	rate = util.randf()
