extends Node

var file_name = "config.cfg"

const DEFAULT_SETTINGS := {
	"client_auth": {
		"broadcaster_username": "username_goes_here",
		"bot_username": "username_goes_here",
		"client_id": "client_id_goes_here",
		"redirect_url": "http://localhost:7170",
	},
	"basic": {
		"skip_obs_crop_warning": false,
		"prevent_bot_message_tts": false,
		"tts_volume": 50,
		"magick_path": "path/to/magick/executable",
		"censor_images_until_approved": true,
	}
}

var settings := {}


func _init():
	_load_settings()


func _load_settings():
	var config := ConfigFile.new()
	var err := config.load(SystemManager.get_program_path().path_join(file_name))

	if err != OK:
		_write_default_config(config)
		config.load(SystemManager.get_program_path().path_join(file_name))

	settings = {}
	for section in DEFAULT_SETTINGS.keys():
		settings[section] = {}
		for key in DEFAULT_SETTINGS[section].keys():
			settings[section][key] = config.get_value(
				section,
				key,
				DEFAULT_SETTINGS[section][key]
			)


func _save_settings():
	var config := ConfigFile.new()

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

	config.save(SystemManager.get_program_path().path_join(file_name))


func get_setting(section: String, key: String) -> Variant:
	if settings.has(section) and settings[section].has(key):
		return settings[section][key]
	return DEFAULT_SETTINGS.get(section, {}).get(key, null)


func set_setting(section: String, key: String, value: Variant):
	if not settings.has(section):
		settings[section] = {}
	settings[section][key] = value
	_save_settings()


func _write_default_config(config: ConfigFile):
	for section in DEFAULT_SETTINGS.keys():
		for key in DEFAULT_SETTINGS[section].keys():
			config.set_value(section, key, DEFAULT_SETTINGS[section][key])
	config.save(SystemManager.get_program_path().path_join(file_name))


func open_settings_file():
	var path := ProjectSettings.globalize_path(SystemManager.get_program_path().path_join(file_name))
	OS.shell_open(path)


func open_readme_file():
	var folder = SystemManager.get_program_path().path_join(file_name).get_base_dir()
	var readme_path = folder.path_join("README.txt")
	var full_path := ProjectSettings.globalize_path(readme_path)
	OS.shell_open(full_path)
