class_name NPCCar
extends PathFollow2D

@export var car : Car
@export var distanceMax = 100

var astar_grid: AStarGrid2D
var toFollow: Array[Vector2i]
@export var world: TileMapLayer

var CARLAYER = 1

func _ready() -> void:
	astar_grid = AStarGrid2D.new()
	astar_grid.region = world.get_used_rect()
	astar_grid.cell_size = Vector2(48, 48)
	astar_grid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_AT_LEAST_ONE_WALKABLE
	astar_grid.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
	astar_grid.default_estimate_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
	astar_grid.update()

	# only take into account the tiles that are marked with a navigation layer for cars
	for x in world.get_used_rect().size.x:
		for y in world.get_used_rect().size.y:
			var tile_position = Vector2(
				x + world.get_used_rect().position.x,
				y + world.get_used_rect().position.y,
			)
			var tile_data = world.get_cell_tile_data(tile_position)
			if tile_data == null or tile_data.get_navigation_polygon(CARLAYER) == null:
				astar_grid.set_point_solid(tile_position)
				

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if car == null:
		return
	# make the wanted position on the track move ahead by a certain amount
	if position.distance_to(car.position) < distanceMax and (toFollow == null or toFollow.is_empty()):
		progress += 200
		# compute the new navigation points the car should follow
		var points = astar_grid.get_id_path(
			world.local_to_map(world.to_local(car.global_position)),
			world.local_to_map(world.to_local(global_position))
		).slice(1)
		if !points.is_empty():
			toFollow = points

	if OS.is_debug_build():
		$Label.text = (
			"position "+str(global_position)+
			"\n, map position "+ str(world.local_to_map(world.to_local(global_position)))+
			"\npoint to follow "+str(toFollow)+
			"\n world position" + str(world.global_position)
			)

	if !toFollow.is_empty():
		if world.local_to_map(world.to_local(car.global_position)) == toFollow.front():
			toFollow.pop_front()
		if !toFollow.is_empty():
			car.moveTo(world.to_global(world.map_to_local(toFollow.front())));
