extends Node

const LANGUAGES_JSON_PATH := "res://localization/languages.json"
const SETTINGS_FILE = "user://settings.cfg"
# dev `user://`=`%APPDATA%\Godot\app_userdata\Skelly`
# prod `user://`=`%APPDATA%\Skelly\`

var settings = {
}

var default_settings = {
	"master_volume": 0.50,
	"music_volume": 0.40,
	"sfx_volume": 0.50,
	"language": "en"
}

var languages_data = {}

func _ready():
	print("SettingsManager ready")
	load_languages()
	load_settings()

func load_settings():
	var config = ConfigFile.new()
	if config.load(SETTINGS_FILE) == OK:
		for key in default_settings.keys():
			settings[key] = config.get_value("settings", key, default_settings[key])
		print("Settings loaded: ", settings)
	else:
		print("No settings file found, using defaults")
	print("Language is set to: ", settings["language"])
	TranslationServer.set_locale(settings["language"])
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear_to_db(settings["master_volume"]))
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Music"), linear_to_db(settings["music_volume"]))
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("SFX"), linear_to_db(settings["sfx_volume"]))


func save_settings():
	var config = ConfigFile.new()
	for key in settings.keys():
		config.set_value("settings", key, settings[key])
	config.save(SETTINGS_FILE)
	print("Settings saved: ", settings)

func get_setting(key: String):
	return settings.get(key)

func set_setting(key: String, value):
	settings[key] = value
	_apply_setting_side_effect(key, value)

func _apply_setting_side_effect(key: String, value) -> void:
	match key:
		"language":
			TranslationServer.set_locale(value)
		"master_volume":
			AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear_to_db(value))
		"music_volume":
			AudioManager.update_music_volume(value)
		"sfx_volume":
			AudioServer.set_bus_volume_db(AudioServer.get_bus_index("SFX"), linear_to_db(value))

func load_languages():
	var file = FileAccess.open(LANGUAGES_JSON_PATH, FileAccess.READ)
	if not file:
		print("Could not open languages.json")
		return

	var json_string = file.get_as_text()
	file.close()

	var json = JSON.new()
	if json.parse(json_string) != OK:
		print("Error parsing languages.json")
		return

	languages_data = json.data
	if languages_data.has("languages"):
		print("Languages loaded: ", languages_data.languages.keys())

func get_languages_data():
	return languages_data

func reset_settings_to_defaults() -> void:
	for key in default_settings.keys():
		settings[key] = default_settings[key]
		_apply_setting_side_effect(key, settings[key])
	save_settings()
