tool
extends Reference
class_name SummerDayZRangeManager

var z_ranges := []


# FIXME: Binary is probably only relevant when readding all the z_ranges
# from a loaded document. But not when adding entirely new ones, as the
# z_index should be aquivalent to the array index.

func load_z_index(z_range_instance):
	var from = z_range_instance._index
	var dest = z_ranges.bsearch_custom(from, self, "_compare_index")
	for i in range(from, z_ranges.size()):
		z_ranges[i]._index += 1
	z_ranges.insert(dest, z_range_instance)
	
	_print_indices()


func add_z_range(z_range_instance):
	var from = z_range_instance._index
	for i in range(from, z_ranges.size()):
		z_ranges[i]._index += 1
	z_ranges.insert(from, z_range_instance)
	
	_print_indices()


func move_z_range(z_range_instance, to: int):
	var from = z_range_instance._index
	
	if from < to: # Index raises.
		z_ranges.remove(from)
		for i in range(from, to):
			z_ranges[i]._index -= 1
		z_ranges.insert(to, z_range_instance)
	else: # Index lowers.
		for i in range(to, from):
			z_ranges[i]._index += 1
		z_ranges.remove(from)
		z_ranges.insert(to, z_range_instance)
	
	_print_indices()


func _compare_index(a, b) -> bool:
	return a._index < b


func _print_indices():
	var debug_str = ""
	for j in z_ranges:
		debug_str += str(j._index) + ",\n"
	SummerDay.debug_info.text = debug_str
