## Gets a range of notes in a NoteData relative to a current beat.
class_name NoteView extends View

## The full set of notes.
@export var notes: NoteArray = null: set = _set_notes

## Get the array this NoteView refers to.
func get_data() -> NoteArray:
	return notes

func update(beat: float) -> void:
	_update_view_relative_to_notes(notes, beat)
	_previous_beat = beat

func reset_view() -> void:
	super.reset_view()
	_previous_beat = -999.0

# ======= IMPLEMENTATION ======= #
var _previous_beat: float = -999.0

func _set_notes(p_notes: NoteArray) -> void:
	notes = p_notes
	reset_view()

## Update the view to match _current_beat.
func _update_view_relative_to_notes(p_notes: NoteArray, new_beat: float) -> void:
	var new_begin = _begin
	var new_end = _end
	if new_beat > _previous_beat:
		# Update forward.
		while(new_begin < p_notes.size()) and (p_notes.beat_at(new_begin) < new_beat + offset_begin):
			new_begin += 1
		while(new_end < p_notes.size()) and (p_notes.beat_at(new_end) <= new_beat + offset_end):
			new_end += 1
	elif new_beat < _previous_beat:
		# Update backward.
		while(new_begin >= 0) and (p_notes.beat_at(new_begin) >= new_beat + offset_begin):
			_begin -= 1
		while(new_end >= 0) and (p_notes.beat_at(new_end) > new_beat + offset_end):
			new_end -= 1
		if(new_begin != _begin):
			new_begin += 1
		if(new_end != _end):
			new_end += 1
	
	_begin = new_begin
	_end = new_end
