extends Node2D

const WAVE_MSG_TIME := 2.0

@export var player_prefab:PackedScene
@export var wave_mgr:WaveManager

@export var ammo_ui:AmmoUI
@export var health_bar:ProgressBar
@export var status:TextFader
@export var dlg:Dialog

var bullet_parent:Node2D
var player:Player

func _ready():
	randomize()
	create_player()

	if Wiper.is_wiped:
		Wiper.unwipe()
		await Wiper.unwiped
	
	# setup some housekeeping nodes
	bullet_parent = Node2D.new()
	bullet_parent.name = "bullets"
	add_child(bullet_parent)
	
	#status.on("Hello", 2.0)
	
	Event.fire_bullet.connect(_on_fire_bullet)
	Event.damage_received.connect(_on_damage_received)
	
	#wave_mgr.wave_changed.connect(func(n:int): status.msg("wave: %d" % n))
	wave_mgr.all_waves_defeated.connect(_on_all_waves_finished)
	wave_mgr.wave_message.connect(_on_wave_message)
	await get_tree().create_timer(1.0).timeout
	wave_mgr.start_next_wave()

func create_player():
	player = player_prefab.instantiate()
	player.global_position = get_viewport_rect().size / 2.0
	add_child(player)
	
	player.health.changed.connect(func(new:float):
		health_bar.value = new
	)
	
	health_bar.max_value = player.health.max_value
	health_bar.value = player.health.max_value
	player.died.connect(_on_lost)
	player.bolts.updated.connect(func(ob:Observable): ammo_ui.num = ob.value)
	player.bolts.emit_manual()

func _on_all_waves_finished():
	status.msg("All waves defeated!", .25, 2.0)
	await status.wait_finished
	player.queue_free()
	status.msg("You Win it all. Unfortunately that's not much.", .25, 2.0)
	await status.wait_finished
	if await dlg.confirm("Exit to Menu"):
		Wiper.wipe_to_scene("res://screens/main_menu.tscn")
	else:
		get_tree().reload_current_scene()
		
func _on_wave_message(msg:String):
	status.msg(msg, 0.25, WAVE_MSG_TIME)
	
func _on_lost():
	status.msg("They Beat you", .25, 1.0)
	await status.wait_finished
	status.msg("Try again", .25, 1.0)
	await status.wait_finished
	
	dlg.msg = "What to do now?"
	dlg.set_buttons(["Quit", "Restart Wave", "Start Over"])
	dlg.show_dlg()
	var res:String = await dlg.closed
	match res:
		"Quit":
			Wiper.wipe_to_scene("res://screens/main_menu.tscn")
		"Restart Wave":
			var spent_bolts:Array = U.get_children(bullet_parent, Bolt)
			for b in spent_bolts:
				b.queue_free()
			
			create_player()
			wave_mgr.restart(false)
		"Start Over":
			get_tree().reload_current_scene()
	
func _on_fire_bullet(b:Bolt, dir:Vector2):
	bullet_parent.add_child(b)
	b.fire(dir)
	
	if bullet_parent.get_child_count() > 50:
		bullet_parent.get_child(0).queue_free()
		
func _on_damage_received(dmg:int, _position:Vector2):
	Mgr.set_text(self, str(dmg), _position  + Vector2.RIGHT * randf_range(-10.0, 10.0), 1.0, Vector2.UP * 40 + Vector2.RIGHT * randf_range(-10.0, 10.0))
