extends PanelContainer

func _ready():
	load_character_inventory()

	#pass

var character_data = []
var getMembers = []

const Rarity = {
	"COMMON":1.0,
	"UNCOMMON": 0.8,
	"RARE": 0.4,
	"SUPERRARE": 0.08, 
	"LEGENDARY": 0.02
}

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(bossTier):
	if character_data.size() == 0:
		print("No characters in inventory.")
		return
	print("Boss tier is:", bossTier)
	getMembers = character_data["members"]
	var rolledcharacter = choose_weighted_random_member(getMembers)
	print("Weighted Character:", rolledcharacter)
	for entry in getMembers:
		if entry["name"] == rolledcharacter["name"]:
			#var random_character = getMembers[entry]
			#print ("Matched", entry["name"], "to", rolledcharacter["name"])
			if not rolledcharacter["isObtained"]:
				rolledcharacter["isObtained"] = true
			rolledcharacter["memberAmount"] += 1
			save_character_inventory()


func choose_weighted_random_member(getMembers):
	var total_weight = 0.0
	for member in getMembers:
		total_weight += Rarity.get(member["rarity"], 0)
	
	var random_value = randf() * total_weight
	var cumulative_weight = 0.0

	for member in getMembers:
		cumulative_weight += Rarity.get(member["rarity"], 0)
		if random_value < cumulative_weight:
			return member
	return null  # Fallback if something goes wrong
