extends Control

@export var spline : Spline
@export var cart : Cart
@export var control_point_scene : PackedScene

@onready var check_button : CheckButton = $HBoxContainer/CheckButton

@export var steps : int = 100

var editing = true

func _ready() -> void:
	pass
	

func _draw():
	if editing:
		for i in range(len(spline.points)-1):
			draw_line(spline.points[i], spline.points[i+1], Color.DIM_GRAY, 1, true)
	
	if len(spline.curve_points) > 2:
		draw_polyline(spline.curve_points, Color.WHITE, 3, true)

func _process(delta: float) -> void:
	if not editing:
		return

	if Input.is_action_just_pressed("add_new_point"):
		var new_control_point : ControlPoint = control_point_scene.instantiate()
		new_control_point.set_represented_position(get_global_mouse_position())
		add_child(new_control_point)
		update()


func update():
	spline.points = []
	for child in get_children():
		if not child is ControlPoint:
			continue
		spline.points.append(child.get_represented_position())
		
		spline.curve_points = []
		for i in range(len(spline.points)-3):
			var b0 : Vector2 = spline.points[i]
			var b1 : Vector2 = spline.points[i+1]
			var b2 : Vector2 = spline.points[i+2]
			var b3 : Vector2 = spline.points[i+3]
			
			var t : float = 0
			while t < 1:
				# B-spline calculations
				var calculated_position =\
					((-b0+3*b1-3*b2+b3)*(t**3) +\
					(3*b0-6*b1+3*b2)*(t**2) +\
					(-3*b0+3*b2)*t +\
					(b0+4*b1+b2))/6
				spline.curve_points.append(calculated_position)
				t += 1.0/steps
		queue_redraw()

func set_editing(toggled_on: bool):
	editing = toggled_on
	for child in get_children():
		if not child is ControlPoint:
			continue
		child.visible = editing
	check_button.button_pressed = toggled_on
	update()

func _on_check_button_toggled(toggled_on: bool) -> void:
	set_editing(toggled_on)


func _on_start_pressed() -> void:
	set_editing(false)
	cart.start()
