class_name GameState extends Resource

# TODO: build dynamically?
var INVENTORY_ITEM_DB := {
	&"meat": load("res://data/meat.tres"),
	&"water_bomb": load("res://data/water_bomb.tres"),
	&"coin_flower": load("res://data/coin_flower.tres"),
	&"coin": load("res://data/coin.tres"),
}

## keys are multiplayer ID ints, values are PlayerData
@export var player_data := {}
## keys are InventoryItem resource IDs (from db),
## values are { "item": InventoryItem, "count": int }
@export var inventory := {}

static var _instance := GameState.new()


static func save() -> void:
	ResourceSaver.save(_instance, "user://game_state.tres")


static func fetch() -> GameState:
	return _instance


static func get_item_count(p_item_id: StringName) -> int:
	if GameState.fetch().inventory.has(p_item_id):
		return GameState.fetch().inventory[p_item_id]["count"]
	else:
		return 0


# TODO: better place for those?
static func are_bundles_stackable(p_a_bundle: Dictionary, p_b_bundle: Dictionary) -> bool:
	var item = GameState.fetch().INVENTORY_ITEM_DB[p_a_bundle["item_id"]]
	return p_a_bundle["item_id"] == p_b_bundle["item_id"] and \
		item.stackable and p_a_bundle["count"] + p_b_bundle["count"] <= item.stack_limit


static func combine_bundles(p_a_bundle: Dictionary, p_b_bundle: Dictionary) -> Dictionary:
	assert(are_bundles_stackable(p_a_bundle, p_b_bundle))
	return {
		"item_id": p_a_bundle["item_id"],
		"count": p_a_bundle["count"] + p_b_bundle["count"],
	}
