extends Node2D

export(String, FILE, "*.tscn") var level_path
var current_level = null
var current_bgm = null

var score = 0

func _ready():
	load_level()

func load_level(next_scene := level_path, fade_out : bool = false):
	if fade_out:
		$HUD.scene_fadeout()
		$BGM/Fader.play("fade_out")
		yield(get_tree().create_timer(2.0), "timeout")
	if current_level != null:
		current_level.hide()
		current_level.queue_free()
		remove_child(current_level)
	current_level = load(next_scene).instance()
	level_path = next_scene
	$HUD.hud_visible(current_level.hud_visible)
	$HUD.set_font_color(current_level.hud_color)
	add_child(current_level)
	play_bgm(current_level.bgm_path)
	$HUD.scene_fadein()
	$BGM.volume_db = 10

func play_bgm(bgm_path):
	var stream
	var file = File.new()
	
	if current_bgm == null or current_bgm != bgm_path and file.file_exists(bgm_path):
		current_bgm = bgm_path
		file.open(bgm_path, file.READ)
		var buffer = file.get_buffer(file.get_len())
		stream = AudioStreamOGGVorbis.new()
		stream.data = buffer
		file.close()
		stream.loop = true
		$BGM.stream = stream
		$BGM.play()
		
func _set_score(value: int):
	score = value
	$HUD.set_score(score)
	
func add_score(value: int):
	_set_score(score + value)

func player_died():
	$HUD.scene_fadeout()
	yield(get_tree().create_timer(1.0), "timeout")
	_set_score(0)
	load_level()
