extends Node2D

@onready var StarScene = preload("res://scenes/Star.tscn")
@onready var PlanetScene = preload("res://scenes/Planet.tscn")

func _ready():
	if GameData.game_lunched == false:
		_generate_galaxy(Settings.NUMBER_OF_SYSTEMS)  # 5 gwiazd testowo
		GameData.game_lunched = true
	print_all_stars_and_planets()


func _generate_galaxy(count: int):
	for i in range(count):
		var star = StarScene.instantiate()
		star.star_name = "Star_" + str(i)
		star.planet_count = randi_range(Settings.min_planet, Settings.max_planet)
		star.global_position = Vector2(randi_range(50, Settings.x), randi_range(50, Settings.y))
		star.get_node("Sprite2D").texture = load("res://assets/stars/s%d.png" % randi_range(1,8))
		add_child(star)
		
		# generowanie planet dla danej gwiazdy
		for j in range(star.planet_count):
			var planet = PlanetScene.instantiate()
			planet.pname = "Planet_" + str(i) + "_" + str(j)
			planet.orbit_radius = 30 + j * 20
			planet.orbit_speed = randf_range(0.01, 0.04)
			generate_planet_resources(planet)  # <-- tu losujemy surowce
			var angle = randf() * TAU
			planet.position = Vector2(cos(angle), sin(angle)) * planet.orbit_radius
			planet.biosfere = randf()  # float od 0 do 1
			if planet.biosfere > 0.7:
				planet.get_node("Sprite2D").texture = load("res://assets/planets/p%d.png" % randi_range(1,9))
			else:
				planet.get_node("Sprite2D").texture = load("res://assets/planets/p%d.png" % randi_range(10,18))
			#planet.get_node("Sprite2D").texture = load("res://assets/planets/p16.png")
			star.add_child(planet)   # Planeta należy do gwiazdy!
			star.planets.append(planet)
			
func print_all_stars_and_planets():
	print("--- Lista gwiazd i planet ---")

	for star in get_children():
		if star is Star:
			print("Gwiazda: ", star.star_name)

			if star.planets.size() == 0:
				print("    (Brak planet)")
			else:
				for planet in star.planets:
					print("Planeta: ", planet.pname, " | Surowiec: ", planet.resource_type)

	print("--- Koniec listy ---")



# Lista wszystkich możliwych surowców
var RESOURCE_TYPES = Settings.RESOURCE_TYPES

func generate_planet_resources(planet):
	planet.resources = {}  # resetujemy słownik
	for res_name in RESOURCE_TYPES:
		var exists = randi() % 100 < 50  # 50% szans na wystąpienie
		var amount = 0
		planet.resources[res_name] = {"exist": exists, "amount": amount}
