extends Control

@export var BPM: float = 140
@export var BeatsInAMeasure: int = 4
var InternalCounter: float = 0
var CurrentNote: int = 0

@export var NoteScene: PackedScene
@export var Path: NodePath

@export_subgroup("sounds")
var CurrentInstrument = 0
@export var PianoSounds: Array[AudioStreamOggVorbis]
@export var PianoNames: Array[String]

# GUI functions above
func _on_exit_pressed():
	get_tree().quit()

func _on_bpm_input_text_changed(new_text):
	BPM = float(new_text)

func _on_measures_text_changed(new_text):
	BeatsInAMeasure = int(new_text)
	var children = get_node("ScrollContainer/VBoxContainer").get_children()
	# Remove everything
	for i in children:
		if i.name != "Line":
			i.free()
	# once the notes were removed, we put the notes again.
	ChangeInstrument(CurrentInstrument)
	CurrentNote = 0

# These are the instrument functions
func _ready():
	ChangeInstrument(0)

func _process(delta):
	InternalCounter = InternalCounter + delta
	if InternalCounter >= (60 / BPM) / 4:
		InternalCounter = 0
		# move the funny line
		CurrentNote = CurrentNote + 1
		if CurrentNote == BeatsInAMeasure * 16:
			CurrentNote = 0
		get_node(Path).position = Vector2(0 + (CurrentNote * 25), 0)

func ChangeInstrument(index: int):
	CurrentInstrument = index
	match index:
		# Piano
		0:
			var newArray = PianoNames.duplicate()
			for i in PianoSounds:
				var thing = NoteScene.instantiate()
				var counter = 0
				thing.SetLabel(newArray.pop_front())
				while BeatsInAMeasure * 4 != counter:
					thing.AddSection(i)
					counter = counter + 1
				get_node("ScrollContainer/VBoxContainer").add_child(thing)
	var sized = get_node("ScrollContainer/VBoxContainer").get_child_count()
	if sized != null:
		get_node(Path).scale = Vector2(1, 25 * sized)

func _on_line_area_entered(area):
	area.get_parent().get_node("Audio").play()
