extends Node

const SAVE_FILE = "savegame.json"

var savegame: Savegame = Savegame.new()

## Dictionary with level_id (int) and level_path (string), order matters and will be the order the levels are presented int
@export var level_information: Dictionary = {
	1 : "res://levels/level_1.tscn",
	2 : "res://levels/level_2.tscn",
	3 : "res://levels/level_3.tscn",
	4 : "res://levels/level_4.tscn",
	5 : "res://levels/level_5.tscn",
	6 : "res://levels/level_6.tscn",
	7 : "res://levels/level_7.tscn",
}

func _ready():
	if savegame_exist():
		read_savegame()
	_savegame_initialization()
	
func delete_savegame() -> void:
	write_savegame("savegame_backup.json")
	savegame = Savegame.new()
	_savegame_initialization()

func _savegame_initialization():
	# Nothing?
	pass

func get_save_folder() -> String:
	var path: String = "user://" + str(0) + "/"
	ensure_path_exists(path)
	return path
	
## Create directory if it does not exist already
func ensure_path_exists(path: String) -> void:
	if not DirAccess.dir_exists_absolute(path):
		print("Creating user save directory...")
		DirAccess.make_dir_recursive_absolute(path)
		print("Created user save directory.")

## Returns the path to a specific save file that's within a user's save folder
func get_path_to_user_file(filename: String) -> String:
	return get_save_folder() + filename

func savegame_exist() -> bool:
	var path = get_path_to_user_file(SAVE_FILE)
	return FileAccess.file_exists(path)
	
func write_savegame(file_name: String = SAVE_FILE) -> void:
	var path = get_path_to_user_file(file_name)
	var file = FileAccess.open(path, FileAccess.WRITE)
	if file == null:
		# error opening file
		var err: Error = FileAccess.get_open_error()
		printerr("Error opening savegame file \"", path, "\" for writing: ", err)
		return
		
	var data = savegame.to_dict()
	var json_string = JSON.stringify(data)
	file.store_string(json_string)
	file.flush()
	file.close()

func read_savegame() -> void:
	var path = get_path_to_user_file(SAVE_FILE)
	var file = FileAccess.open(path, FileAccess.READ)
	if file == null:
		# error opening file
		var err: Error = FileAccess.get_open_error()
		printerr("Error opening savegame file \"", path, "\" for reading: ", err)
		return
	var content = file.get_as_text()
	file.close()
	var data: Dictionary = JSON.parse_string(content)
	
	savegame.apply_dict(data)

func on_savegame_changed():
	write_savegame()

func get_level_completed(level_id: int) -> bool:
	if savegame.level_dict.has(level_id):
		return savegame.level_dict[level_id]
	return false

func level_won(level_id: int):
	savegame.level_dict[level_id] = true

## Returns true if any level has been won, and false if no level at all has been won
func any_level_has_been_won() -> bool:
	for key in savegame.level_dict.keys():
		if savegame.level_dict[key]:
			return true
	return false

func get_level_id_for_scene_path(scene_path: String) -> int:
	for key in level_information.keys():
		if level_information[key] == scene_path:
			return key
	return -1

## Gets the ID of the next level, -1 if current_level_id is the last one or does not exist
func get_next_level_id(current_level_id: int) -> int:
	var return_next: bool = false
	if level_information.has(current_level_id):
		for key in level_information.keys():
			if return_next:
				return key
			if key == current_level_id:
				return_next = true
	return -1
