extends Node2D
class_name Cart

@export var spline : Spline 


var going = false
var progress : float = 0
var velocity = 0
var initial_velocity = 10
var speed_multiplier = 0.1
var initial_height = 0
var last_velocity = 0

var time = 0
var function : Function
var first_tick = false

@export var chart : Chart

func _ready():
	hide()
	function = Function.new(
		[0],
		[0],
		"Acceleration",
		{
			type = Function.Type.LINE,
			marker = Function.Marker.SQUARE,
			color = Color.WHITE,
			interpolation = Function.Interpolation.SPLINE
		}
	)
	var cp: ChartProperties = ChartProperties.new()
	cp.colors.frame = Color("#161a1d")
	cp.colors.background = Color.TRANSPARENT
	cp.colors.grid = Color("#283442")
	cp.colors.ticks = Color("#283442")
	cp.colors.text = Color.WHITE_SMOKE
	cp.draw_bounding_box = false
	cp.title = "Roller Coaster Acceleration"
	cp.x_label = "Time"
	cp.y_label = "Acceleration (m/s^2)"
	cp.x_scale = 5
	cp.y_scale = 10
	cp.interactive = true
	cp.max_samples = 1000
	
	chart.plot([function], cp)

func start():
	first_tick = true
	for i in range(1000):
		function.remove_point(0)

	initial_height = position.y - initial_velocity
	last_velocity = sqrt(2*9.8*(position.y-initial_height))*speed_multiplier
	velocity = 0
	going = true
	time = 0
	show()
	

func _physics_process(delta: float) -> void:
	var new_point = spline.get_point_at(progress)

	if new_point != null:
		position = new_point
	else:
		going = false
		hide()
		progress = 0

	if not going:
		return
	
	last_velocity = velocity
	velocity = sqrt(2*9.8*(position.y-initial_height))*speed_multiplier
	progress += velocity
	time += delta
	
	if not first_tick:
		function.add_point(time, velocity-last_velocity)
	
	chart.queue_redraw()
	
	if first_tick:
		first_tick = false
	
		
