extends Node

const REACTIONS_DIRECTORY = "res://assets/reactions/"

@export var water_soluable: Array[Substance] = [preload("res://assets/substances/AgNO3.tres"),preload("res://assets/substances/CaCl.tres"),preload("res://assets/substances/CaCO3.tres"),preload("res://assets/substances/CH3COONa.tres"),preload("res://assets/substances/CuSO4.tres"),preload("res://assets/substances/FeSO4.tres"),preload("res://assets/substances/KCl.tres"),preload("res://assets/substances/KI.tres"),preload("res://assets/substances/KNO3.tres"),preload("res://assets/substances/LeadNitrate.tres"),preload("res://assets/substances/MethylOrange.tres"),preload("res://assets/substances/Na2CO3.tres"),preload("res://assets/substances/Na2S.tres"),preload("res://assets/substances/Na2SO4.tres"),preload("res://assets/substances/NaCl.tres"),preload("res://assets/substances/NaNO3.tres"),preload("res://assets/substances/NaOH.tres"),preload("res://assets/substances/NH4CL.tres"),preload("res://assets/substances/NH4OH.tres"),preload("res://assets/substances/Phenolphtalein.tres")]

var reactions: Array[Reaction]

func _ready() -> void:
	for file in ResourceLoader.list_directory(REACTIONS_DIRECTORY):
		reactions.append(load(REACTIONS_DIRECTORY + file))

func find_appropriate_reaction(input_substances: Array[Substance], temperature: float) -> Reaction:
	var has_all: Callable = func(compared_array: Array[ReactionSubstance]) -> bool:
		for el in compared_array:
			if not el.substance in input_substances:
				return false
		return true
	
	var filter_func: Callable = func(reaction: Reaction) -> bool:
		if reaction.reaction_temperature != -1:
			return (has_all.call(reaction.input_substances)) and temperature >= reaction.reaction_temperature
		else:
			return has_all.call(reaction.input_substances)
	
	var filtered: Array[Reaction] = reactions.filter(filter_func)
	
	if len(filtered) > 0:
		return filtered[0]
	else:
		return null

func is_water_solution(substance: Substance):
	return water_soluable.has(substance)
