extends MeshInstance3D

enum DisplayType{
	Fluid,
	Solid,
}

@export var display_type: DisplayType

func update_material(substances: Array[RuntimeSubstanceData]) -> void:
	var mat: StandardMaterial3D = material_override
	if len(substances) == 0:
		visible = false
		return
	else:
		visible = true
		
	var total_weight = 0
	var total_color = 0

	for sub in substances:
		total_weight += sub.amount
		total_color += sub.substance.color_influence
	
	var pH: float = 0
	var color: Color = Color(0,0,0,0)

	for sub: RuntimeSubstanceData in substances:
		var weight: float = sub.amount/total_weight
		pH += sub.substance.get_ph_runtime(substances) * weight
	
	for sub: RuntimeSubstanceData in substances:
		var color_to_add: Color
		if sub.substance.pHColor != null:
			color_to_add =  sub.substance.pHColor.sample(pH/14.0)
		else:
			color_to_add = sub.substance.color
			
		if display_type == DisplayType.Fluid and sub.is_solution:
			color_to_add.a = 0.5
		
		#if color == Color(0,0,0,0):
		#	color = color_to_add
		#else:
		#	color = color.lerp(color_to_add,sub.substance.color_influence)
		color += color_to_add * sub.substance.color_influence
	
	
	mat.albedo_color = color / total_color

func update_material_unfiltered(substances: Array[RuntimeSubstanceData]):
	match display_type:
		DisplayType.Fluid:
			var fluids = substances.filter(filter_liquids)
			update_material(fluids)
		DisplayType.Solid:
			var solids = substances.filter(filter_solids)
			update_material(solids)

func filter_liquids(sub: RuntimeSubstanceData): return sub.substance.melting_point < sub.temperature or sub.is_solution
func filter_solids(sub: RuntimeSubstanceData): return sub.substance.melting_point > sub.temperature and not sub.is_solution
