extends PanelContainer

func _ready():
	load_character_inventory()
	#pass

var character_data = []
var getMembers = []

func load_character_inventory():
	var file_path = "user://MemberDatabase/memberData.json"
	if FileAccess.file_exists(file_path):
		var file = FileAccess.open(file_path, FileAccess.READ)
		if file:
			var json_text = file.get_as_text()
			file.close()
			#print("Loaded JSON text: ", json_text)
			
			var json_parser = JSON.new()
			var json_result = json_parser.parse(json_text)
			
			if json_result == OK:
				#character_data = json_result.result.get("members", [])
				character_data = json_parser.get_data()
				#print("Loaded character data: ", character_data)
			else:
				print("Error parsing JSON: ", json_result.error_string)
		else:
			print("Failed to open file: ", file_path)
	else:
		print("File not found: ", file_path)
	

func save_character_inventory():
	var file_path = "user://MemberDatabase/memberData.json"
	var file = FileAccess.open(file_path, FileAccess.WRITE)
	if file:
		var json_text = JSON.stringify({ "members": getMembers })
		file.store_string(json_text)
		file.close()
		#print("Saved character data: ", json_text)
	else:
		print("Failed to open file: ", file_path)



func update_character(index, new_data):
	if index >= 0 and index < character_data.size():
		character_data[index] = new_data
		save_character_inventory()
		#print("Updated character data: ", character_data[index])
	else:
		print("Invalid character index: ", index)

func roll_character():
	if character_data.size() == 0:
		print("No characters in inventory.")
		return
	getMembers = character_data["members"]
	var random_index = randi() % getMembers.size()
	var random_character = getMembers[random_index]
	if not random_character["isObtained"]:
		random_character["isObtained"] = true
	random_character["memberAmount"] += 1
	save_character_inventory()
	print("Rolled character: ", random_character["name"])


