extends Node

## Used Settings object
var settings: Settings = Settings.new()

var first_time_game_start: bool = false

const SAVE_FILE = "settings.json"

func _ready():
	if saved_settings_exist():
		read_settings()
	else:
		_first_time_starting()
	settings.settings_changed.connect(_on_settings_changed)

func _on_settings_changed():
	write_settings()

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 saved_settings_exist() -> bool:
	var path = get_path_to_user_file(SAVE_FILE)
	return FileAccess.file_exists(path)

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

func _first_time_starting() -> void:
	first_time_game_start = true
	
	# Apply settings (window mode, default audio levels, etc)
	settings.apply_dict(settings.to_dict())

func read_settings() -> 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 settings file \"", path, "\" for reading: ", err)
		return
	var content = file.get_as_text()
	file.close()
	var data: Dictionary = JSON.parse_string(content)
	
	settings.apply_dict(data)
