extends MultiMeshInstance3D

var mm: MultiMesh
var parent_node: FlowerController
static var flower_mesh: Mesh = null
var material: StandardMaterial3D

func _ready() -> void:
	parent_node = get_parent() as FlowerController
	if parent_node == null:
		Log.pr("Error: Parent node is not a FlowerController!")
	
	# Load mesh once and reuse
	if flower_mesh == null:
		flower_mesh = load("res://Entities/Plant/assets/flower_tall.res")

func setup_multimesh() -> void:
	if parent_node == null:
		return
	
	if flower_mesh == null:
		Log.pr("Error: Could not load flower mesh")
		return
	
	# Reuse existing MultiMesh if possible, or create new one
	if mm == null:
		mm = MultiMesh.new()
		mm.transform_format = MultiMesh.TRANSFORM_3D
		mm.mesh = flower_mesh

		var flower_material = ColorData.flower_materials[Season.current]["flower"]
		var stem_material = ColorData.flower_materials[Season.current]["stem"]
		mm.mesh.surface_set_material(0, stem_material)
		mm.mesh.surface_set_material(1, flower_material)
	
	# Configure instance count
	mm.instance_count = parent_node.flower_instance_range
	
	# Get shared RNG from GroundTile
	var rng = parent_node.parent_node.get_rng()
	
	# Generate positions using shared RNG
	for i in range(mm.instance_count):
		var random_pos = Vector3(
			rng.randf_range(-1.0, 1.0),
			0.0,
			rng.randf_range(-1.0, 1.0)
		)
		
		var random_rotation = rng.randf_range(0.0, TAU)
		var basis = Basis(Vector3.UP, random_rotation)
		
		var random_scale = rng.randf_range(0.2, 0.4)
		basis = basis.scaled(Vector3(random_scale, random_scale, random_scale))
		
		var tx = Transform3D(basis, random_pos)
		mm.set_instance_transform(i, tx)

	multimesh = mm
