extends Path2D

enum { UP, RIGHT, DOWN, LEFT }

var tile_size : int = 128
var half_size : int = tile_size / 2
onready var map = get_node("../TileMap/")

# Called when the node enters the scene tree for the first time.
func _ready():
	var track = TrackSelection.get_current_track()
	_build_track(track)


func _draw():
	draw_polyline(curve.get_baked_points(), Color.chartreuse, 4.0)
	for idx in range(0,curve.get_point_count()):
		draw_circle(curve.get_point_in(idx), 2.0, Color.green)
		draw_circle(curve.get_point_out(idx), 2.0, Color.blue)


func _build_track(tiles):
	""" Build the track curve given a tile path """
	var _curve = get_curve()
	_curve.clear_points()
	# Set start point
	var start_point = map.map_to_world(tiles[0])
	start_point.y += half_size
	start_point.x += half_size
	_point_at(_curve, start_point, RIGHT)
	for idx in range(0, tiles.size()):
		var next_idx = idx + 1 if idx < tiles.size() - 1 else 0
		var dir = _direction_to(tiles[idx], tiles[next_idx])
		# Find position of next point
		var pos = map.map_to_world(tiles[idx])
		match dir:
			# We start from upper left corner
			UP: pos = Vector2(pos.x + half_size, pos.y)
			RIGHT: pos = Vector2(pos.x + tile_size, pos.y + half_size)
			DOWN: pos = Vector2(pos.x + half_size, pos.y + tile_size)
			LEFT: pos = Vector2(pos.x, pos.y + half_size)
		_point_at(_curve, pos, dir)
	_point_at(_curve, start_point, RIGHT)
	set_curve(_curve)
	print_debug("Built track !", _curve)
# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass

func _point_at(_curve, pos, dir):
	# Use only control_in since it gives smoother turns
	var half_size = tile_size / 2
	var control_in
	match dir:
		DOWN: 
			control_in = Vector2(0, - half_size)
			#control_out = Vector2(0, half_size)
		UP: 
			control_in = Vector2(0, half_size)
			#control_out = Vector2(0, -half_size)
		RIGHT: 
			control_in = Vector2( - half_size, 0)
			#control_out = Vector2(half_size, 0)
		LEFT:
			control_in = Vector2(half_size, 0)
			#control_out = Vector2(-half_size, 0)
	#print_debug("Add point: ", pos, ", in=", control_in), " out=", control_out, " | ", dir)
	_curve.add_point(pos, control_in) #, control_out)
	

func _direction_to(from_tile, to_tile):
	var x_dir = to_tile.x - from_tile.x
	var y_dir = to_tile.y - from_tile.y
	if abs(x_dir + y_dir) == 1:
		if x_dir == 1:
			return RIGHT
		elif x_dir == -1:
			return LEFT
		elif y_dir == 1:
			return DOWN
		elif y_dir == -1:
			return UP
	else:
		print_debug("Panic!! Path is not contiguous between", from_tile, " and ", to_tile)