extends Resource
class_name Settings

var version: int = 1
signal settings_changed

var window_mode: DisplayServer.WindowMode = (DisplayServer.WINDOW_MODE_WINDOWED as DisplayServer.WindowMode) :
	set(value):
		window_mode = (value as DisplayServer.WindowMode)
		_set_window_mode(value)
		settings_changed.emit()

var volume_master: int = 90 :
	set(value):
		volume_master = value
		_set_volume_master(value)
		settings_changed.emit()
		
var volume_music: int = 60:
	set(value):
		volume_music = value
		_set_volume_music(value)
		settings_changed.emit()
		
var volume_sound_effects: int = 90:
	set(value):
		volume_sound_effects = value
		_set_volume_sound_effects(value)
		settings_changed.emit()

func to_dict():
	var data = {
		"version" : version,
		"window_mode" : window_mode,
		"volume_master" : volume_master,
		"volume_music" : volume_music,
		"volume_sound_effects" : volume_sound_effects,
	}
	return data

func apply_dict(data):
	if (data.version != version):
		print("Saved version is ", data.version, " but game uses version ", version)
	
	window_mode = data.window_mode
	volume_master = data.volume_master
	volume_music = data.volume_music
	volume_sound_effects = data.volume_sound_effects

func _set_window_mode(value: DisplayServer.WindowMode):
	DisplayServer.window_set_mode(value)

func _set_volume_master(value):
	_change_bus_volume("Master", value)

func _set_volume_music(value):
	_change_bus_volume("Music", value)
	
func _set_volume_sound_effects(value):
	_change_bus_volume("SoundEffects", value)

func _change_bus_volume(bus_name: String, value: float):
	if(value == 0):
		AudioServer.set_bus_mute(AudioServer.get_bus_index(bus_name), true)
		return
	else:
		AudioServer.set_bus_mute(AudioServer.get_bus_index(bus_name), false)
		
		var sliderMaxValue: float = 100.0
		var percentage: float = value / sliderMaxValue
		var EPSILON: float = 0.00001
		if percentage < EPSILON:
			percentage = EPSILON
			
		var log10 = log(percentage) / log(10)
		var dbBValue = log10 * 20
		AudioServer.set_bus_volume_db(AudioServer.get_bus_index(bus_name), dbBValue)
