extends Node
"""
Used to cache data for faster subsequent retrieval

Should only cache data that does not need to be freed manually, so things that
are OK to cache include objects that inherit `Reference` and built-ins
"""

const TYPE_IMAGE: String = "image"
const TYPE_DICTIONARY: String = "dictionary"
const TYPE_ARRAY: String = "array"
const TYPE_RESOLVED_URL: String = "resolved_url"

# Stores cached resources. "resources" as in the general meaning of the word,
# not specifically things that inherit the `Resource` class
var _cached_resources: Dictionary = {}


func _init() -> void:
	for type in [TYPE_IMAGE, TYPE_DICTIONARY, TYPE_ARRAY, TYPE_RESOLVED_URL]:
		_cached_resources[type] = {}


func add_image(id: String, img: Image) -> void:
	if len(id) == 0:
		return
	_cached_resources[TYPE_IMAGE][id] = img


func get_image(id: String) -> Image:
	var img: Image = _cached_resources.get(TYPE_IMAGE, {}).get(id)
	if img and is_instance_valid(img):
		return img
	return null


func add_dictionary(id: String, dict: Dictionary) -> void:
	if len(id) == 0:
		return
	_cached_resources[TYPE_DICTIONARY][id] = dict


func get_dictionary(id: String) -> Dictionary:
	var dict: Dictionary = _cached_resources.get(TYPE_DICTIONARY, {}).get(id)
	return dict


func add_array(id: String, arr: Array) -> void:
	if len(id) == 0:
		return
	_cached_resources[TYPE_ARRAY][id] = arr


func get_array(id: String) -> Array:
	var arr: Array = _cached_resources.get(TYPE_ARRAY, {}).get(id, [])
	return arr


func add_resolved_url(id: String, dict: Dictionary) -> void:
	if len(id) == 0:
		return
	_cached_resources[TYPE_RESOLVED_URL][id] = dict


func get_resolved_url(id: String) -> Dictionary:
	var dict: Dictionary = \
			_cached_resources.get(TYPE_RESOLVED_URL, {}).get(id, {})
	return dict
