extends Node

signal settings_changed

const SETTINGS_PATH: String = "user://settings.cfg"

var settings: Dictionary[String, Dictionary] = {
	&"game": {
		&"has_compiled_shaders": false,
	},
	&"audio": {
		&"Master": 1.0,
		&"SFX": 1.0,
		&"Music": 1.0,
		&"Ambient": 1.0,
	},
	&"video": {
		&"fullscreen": true
	},
	&"misc": {
		&"language": -1,
		&"headbobbing": true
	}
}


func _ready() -> void:
	load_settings()


func load_settings() -> void:
	if not FileAccess.file_exists(SETTINGS_PATH):
		save_settings()
		return

	var config := ConfigFile.new()
	config.load(SETTINGS_PATH)

	for section: String in settings.keys():
		for key: String in settings[section].keys():
			var default: Variant = get_setting(section, key)
			set_setting(section, key, config.get_value(section, key, default), false)


func save_settings() -> void:
	var config := ConfigFile.new()

	for section: String in settings.keys():
		for key: String in settings[section].keys():
			config.set_value(section, key, settings[section][key])

	config.save(SETTINGS_PATH)


func set_setting(section: String, key: String, value: Variant, do_save: bool = true) -> void:
	settings[section][key] = value
	settings_changed.emit()

	if do_save:
		save_settings()


func get_setting(section: String, key: String) -> Variant:
	return settings[section][key]


func adjust_volume(bus: StringName, volume: float) -> void:
	set_setting(&"audio", bus, volume, false)


func set_fullscreen(fullscreened: bool) -> void:
	DisplayServer.window_set_mode(
		DisplayServer.WINDOW_MODE_FULLSCREEN if fullscreened else DisplayServer.WINDOW_MODE_WINDOWED
	)
	set_setting(&"video", &"fullscreen", fullscreened)


func set_language(index: int) -> void:
	set_setting(&"misc", &"language", index)
