class_name Item
extends Resource


enum Category {
	CATEGORY_NONE = 0,
	CATEGORY_FOOD = 1 << 0,
	CATEGORY_TOOL = 1 << 1,
	CATEGORY_PAPER = 1 << 2,
	CATEGORY_GEM = 1 << 3,
	CATEGORY_CURRENCY = 1 << 4,
	CATEGORY_CONTAINER = 1 << 5,
	CATEGORY_MAGIC = 1 << 6,
	CATEGORY_NUM = 1 << 7,
}

enum State {
	STATE_NONE = 0,
	STATE_CURSED = 1 << 0,
	STATE_BANNED = 1 << 1,
	STATE_WET = 1 << 2,
	STATE_NUM = 1 << 3,
}

@export var icon: Texture2D = preload("res://icon.svg")
@export var name := "Static"
@export var id := &"static"
@export_multiline var description := "Your eyes begin to mist over."
@export_flags(
	"Food",
	"Tool",
	"Paper",
	"Gem",
	"Currency",
	"Container",
	"Magic",
) var categories := 0
@export_range(0, 255) var intrinsic_value := 0

@export var weight := 0
@export var stackable := true
@export var stack_size := 6

## Affects condition of food items
@export var spoilage_per_day := 0

@export var condition := 100 # 0 (broken) to 100 (spotless)
@export var states := 0
@export var amount := 1 # increased when stacked


func _init() -> void:
	resource_name = id


func category_to_string(category: Category) -> String:
	match category:
		Category.CATEGORY_NONE:
			return "none"
		Category.CATEGORY_FOOD:
			return "food"
		Category.CATEGORY_TOOL:
			return "tool"
		Category.CATEGORY_PAPER:
			return "paper"
		Category.CATEGORY_GEM:
			return "gem"
		Category.CATEGORY_CURRENCY:
			return "currency"
		Category.CATEGORY_CONTAINER:
			return "container"
		Category.CATEGORY_MAGIC:
			return "magic"
		_:
			assert(false, "tried to get string representation of invalid category bit")
			return "bugged"


func category_list(capitalize := true, add_commas := true) -> String:
	var strings: PackedStringArray
	
	var current_bit: int = Category.CATEGORY_NUM
	while current_bit > Category.CATEGORY_NONE:
		if categories & current_bit:
			strings.push_back(category_to_string(current_bit))
		
		current_bit >>= 1
	
	if capitalize:
		strings[0] = strings[0].to_pascal_case()
	
	if add_commas:
		return ", ".join(strings)
	else:
		return " ".join(strings)


func state_to_string(state: State) -> String:
	match state:
		State.STATE_NONE:
			return "none"
		State.STATE_CURSED:
			return "cursed"
		State.STATE_BANNED:
			return "banned"
		State.STATE_WET:
			return "wet"
		_:
			assert(false, "tried to get string representation of invalid state bit")
			return "bugged"


func state_list(capitalize := true, add_commas := true) -> String:
	var strings: PackedStringArray
	
	var current_bit: int = State.STATE_NUM
	while current_bit > State.STATE_NONE:
		if states & current_bit:
			strings.push_back(state_to_string(current_bit))
		
		current_bit >>= 1
	
	if capitalize:
		strings[0] = strings[0].to_pascal_case()
	
	if add_commas:
		return ", ".join(strings)
	else:
		return " ".join(strings)


func worsen_condition(by: int) -> void:
	condition -= by
	condition = clamp(condition, 0, 100)


func improve_condition(by: int) -> void:
	condition += by
	condition = clamp(condition, 0, 100)
