tool
extends Resource
class_name SummerDayTable


export(int) var allocation_size # How many matrices per frame.
export(ImageTexture) var texture
export(Image) var image

var dirty_flag = false


func create():
	print("created")
	var row_size = allocation_size * 4
	texture = ImageTexture.new()
	image = Image.new()
	image.create(row_size, 1, false, Image.FORMAT_RGBAF)
	texture.create_from_image(image, 0)
	_presage_changes()
	image.fill(Color.red)
	flush()


# Position in matrix-indices, not in pixels.
func apply_matrix(matrix: SummerDayMatrix4, row: int, position: int):
	_presage_changes()
	var color_list = matrix.get_values_as_colors()
	for i in range(4):
		image.set_pixel(
			position * 4 + i,
			row, color_list[i]
		)


func add_row():
	_presage_changes()
	image.crop(image.get_width(), image.get_height() + 1)


func remove_row(at: int):
	_presage_changes()
	var size = image.get_size()
	var below_height = size.y - 1
	if at < below_height:
		image.blit_rect(image,
			Rect2(Vector2(0, at + 1), Vector2(size.x, below_height - at)),
			Vector2(Vector2(0, at))
		)
	image.crop(size.x, below_height)


func flush():
	if dirty_flag:
		image.unlock()
		texture.set_data(image)
		dirty_flag = false


# This needs to be called before anything, that makes changes to the image!
func _presage_changes():
	if !dirty_flag:
		image.lock()
		dirty_flag = true
