extends Node

signal player_died(death_type: DeathTypes)

const MAIN_MENU_PATH: String = "uid://dwd8wf02j2epn"
const INITIAL_LEVEL_ID: StringName = &"OutsideArea"
const GAME_PATH: String = "uid://s7cw6ulb7kh7"
const PLAYER_PATH: String = "uid://clhy3kiceqf2o"
const CHAPTER_LIST: ChapterList = preload("uid://d2mcwotliowv7")
const LEVELS: Dictionary[StringName, String] = {
	&"OutsideArea": "uid://lraild3yetsh",
	&"EntranceHall": "uid://cmdy6f6kesmbj",
}

enum DeathTypes {
	SAW,
}

var game: Game
var level: StringName = &""
var player: PlayerCharacter
var player_alive: bool = true
var spawn_id: StringName = &"": set = set_spawn_id
var chapter_index: int = 0: set = set_chapter_index
var in_cutscene: bool = false


func get_player() -> PlayerCharacter:
	return player


func reset_game() -> void:
	player_alive = true
	spawn_id = &""
	level = INITIAL_LEVEL_ID
	chapter_index = 0
	in_cutscene = false


func load_from_save() -> void:
	SaveManager.load_game()

	var data: Dictionary[StringName, Variant] = SaveManager.persistent_data
	spawn_id = data.get(&"spawn_id")
	chapter_index = data.get(&"chapter_index")
	level = data.get(&"level", &"")


func set_spawn_id(id: StringName) -> void:
	spawn_id = id

	SaveManager.persistent_data[&"spawn_id"] = spawn_id


func set_chapter_index(index: int) -> void:
	chapter_index = index

	SaveManager.persistent_data[&"chapter_index"] = chapter_index


func set_level(level_id: StringName) -> void:
	level = level_id

	SaveManager.persistent_data[&"level"] = level


func kill_player(death_type: DeathTypes) -> void:
	if not player_alive:
		return

	get_tree().paused = true

	SPrint.print_msg(
		"Killed player. Death Type: %s" % death_type, -1.0, SPrint.NORMAL_RICH, Color.ORANGE_RED
	)

	if is_instance_valid(player):
		player.process_mode = Node.PROCESS_MODE_DISABLED

	AudioManager.flush_audio_by_bus(AudioManager.SFX)
	AudioManager.flush_audio_by_bus(AudioManager.MUSIC)
	AudioManager.flush_audio_by_bus(AudioManager.AMBIENCE)

	player_alive = false
	player_died.emit(death_type)
