extends Spatial

class_name Route

signal road_added(road)
signal road_removed(road)


func get_last_road():
	if get_child_count() > 0:
		return get_child(get_child_count() - 1)
	else:
		return null


func get_road(road_index):
	if road_index >= 0 && get_child_count() > road_index:
		return get_child(road_index)
	else:
		return null


master func add_road(type):
	if is_network_master():
		var sender_id = get_tree().get_rpc_sender_id()
		if sender_id == 0:
			sender_id = 1
		var creator = gamestate.game.get_player_by_network_id(sender_id)
		if creator != null && creator.is_in_group("first"):
			set_road(type,creator.get_name())
			rpc("set_road", type, creator.get_name())


puppet func set_road(type, creator):
	var transform = get_global_transform()
	var last_road = get_last_road()
	if last_road != null:
		transform = last_road.get_global_transform();
		var curve = last_road.get_curve()
		transform = transform.translated(curve.get_point_position(curve.get_point_count() - 1))
		if last_road.get_end_rotation().length() != 0:
			transform.basis = transform.basis.rotated(last_road.get_end_rotation().normalized(), last_road.get_end_rotation().length())

	var new_road = roads_factory.get_road_instance(type)
	new_road.set_global_transform(transform)
	new_road.set_preview(false)
	new_road.set_creator(creator)

	var player = gamestate.game.get_player(str(creator))
	if player != null:
		new_road.set_color(player.get_player_color())

	add_child(new_road)

	emit_signal("road_added", new_road)


remotesync func remove_road(road_index):
	var road = get_child(road_index)
	remove_child(road)
	emit_signal("road_removed", road)