extends Node2D

class_name Main

func _ready():
	connect_player_properties_update()
	connect_level_update()
	connect_button()
	init_bgm()

func connect_player_properties_update():
	var player = get_level_manager().get_current_level_instance().get_player()
	player.connect("hp_changed",self,"on_hp_changed")
	player.connect("atk_changed",self,"on_atk_changed")
	player.connect("def_changed",self,"on_def_changed")
	player.connect("money_changed",self,"on_money_changed")
	player.connect("yellow_key_changed",self,"on_yellow_key_changed")
	player.connect("blue_key_changed",self,"on_blue_key_changed")
	player.connect("red_key_changed",self,"on_red_key_changed")

func connect_button():
	$"/root/Main/HUD/BottomBackground/VBoxContainer/SaveButton".connect("pressed",self,"on_save_button_clicked")
	$"/root/Main/HUD/BottomBackground/VBoxContainer/LoadButton".connect("pressed",self,"on_load_button_clicked")
	
func connect_level_update():
	get_level_manager().connect("level_changed",self,"on_level_changed")

func init_bgm():
	var audio_player = $BgmSound as AudioStreamPlayer2D
	audio_player.playing = true

func on_hp_changed(hp):
	get_hud().get_hp_view().text = hp as String

func on_atk_changed(atk):
	get_hud().get_atk_view().text = atk as String
	
func on_def_changed(def):
	get_hud().get_def_view().text = def as String
	
func on_money_changed(money):
	get_hud().get_money_view().text = money as String
	
func on_yellow_key_changed(yellow_key):
	get_hud().get_yellow_key_view().text = "%0*d" % [2,yellow_key]
	
func on_blue_key_changed(blue_key):
	get_hud().get_blue_key_view().text = "%0*d" % [2,blue_key]

func on_red_key_changed(red_key):
	get_hud().get_red_key_view().text = "%0*d" % [2,red_key]

func on_level_changed(level):
	connect_player_properties_update()
	get_hud().get_level_view().text = "%s层" % level

func on_save_button_clicked():
	get_level_manager().save_persistent(0)

func on_load_button_clicked():
	get_level_manager().load_persistent(0)

func get_hud() -> Hud:
	return $HUD as Hud

func get_level_manager() -> LevelsManager:
	return $Level as LevelsManager
