extends TileMap

enum { LEFT, RIGHT, UP, DOWN }
# Enum for tiles from tile_set
enum { DOWN_LEFT, DOWN_RIGHT, LEFT_RIGHT, START, UP_DOWN, UP_LEFT, UP_RIGHT }

# Called when the node enters the scene tree for the first time.
func _ready():
	_clear_tiles()
	var track = TrackSelection.get_current_track()
	for idx in range(track.size()):
		var cell = track[idx]
		var tile
		if idx == 0:
			tile = START
		else:
			var prev = track[idx - 1]
			var next = track[wrapi(idx + 1, 0, track.size())]
			tile = _find_tile(cell.direction_to(prev), cell.direction_to(next))
		set_cell(cell.x, cell.y, tile)

func _find_tile(prev, next):
	""" Find the right tile given prev and next directions """
	prev = _as_dir(prev)
	next = _as_dir(next)
	# Could be smarter
	if prev == LEFT:
		match next:
			DOWN: return DOWN_LEFT
			UP: return UP_LEFT
			RIGHT: return LEFT_RIGHT
	elif prev == RIGHT:
		match next:
			DOWN: return DOWN_RIGHT
			UP: return UP_RIGHT
			LEFT: return LEFT_RIGHT
	elif prev == UP:
		match next:
			DOWN: return UP_DOWN
			LEFT: return UP_LEFT
			RIGHT: return UP_RIGHT
	elif prev == DOWN:
		match next:
			UP: return UP_DOWN
			LEFT: return DOWN_LEFT
			RIGHT: return DOWN_RIGHT
			
	
func _as_dir(vector):
	""" Returns the vector direction as a LEFT, RIGHT, UP or DOWN variant """
	if abs(vector.x) + abs(vector.y) != 1:
		return -1  # This is not a valid variant
	if vector.x == -1:
		return LEFT
	elif vector.x == 1:
		return RIGHT
	elif vector.y == -1:
		return UP
	elif vector.y == 1:
		return DOWN
	return -1  # Impossible case

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass

func _clear_tiles():
	for cell in get_used_cells():
		self.set_cell(cell.x, cell.y, -1)