extends Node

enum ScreenMode {
	FULLSCREEN = 0,
	WINDOWED = 1,
}

const PATH: String = "user://.config"

var palette: int = 0
var screen_mode: ScreenMode = ScreenMode.FULLSCREEN
var master_volume: int = 8
var sounds_volume: int = 8
var music_volume: int = 6

var _palletes: Array[GBPalette] = [
	load("uid://dhyomieciwaky"),
	load("uid://6ac3efe5r4gi"),
	load("uid://b8kf5jlwqabq5"),
	load("uid://7cfxg7gqka6s"),
	load("uid://ch4f3kc13b8c2"),
	load("uid://b160a1c1drbmt")
]
var _config: ConfigFile = ConfigFile.new()



func _init() -> void:
	var err: Error = _config.load(PATH)
	if not err:
		load_settings()
	elif err == ERR_FILE_NOT_FOUND:
		save_settings()
	Input.mouse_mode = Input.MOUSE_MODE_HIDDEN


func _ready() -> void:
	DisplayServer.window_set_min_size(Vector2i(160, 144))


func get_current_palette() -> GBPalette:
	return _palletes[palette]


func load_settings() -> void:
	palette = clampi(_config.get_value("settings", "palette", 0), 0, 5)
	screen_mode = ScreenMode.values()[clampi(_config.get_value("settings", "window_mode", 0), 0, 1)]
	master_volume = clampi(_config.get_value("settings", "master_volume", 8), 0, 8)
	sounds_volume = clampi(_config.get_value("settings", "sounds_volume", 8), 0, 8)
	music_volume = clampi(_config.get_value("settings", "music_volume", 6), 0, 8)
	set_settings()



func save_settings() -> void:
	_config.set_value("settings", "palette", palette)
	_config.set_value("settings", "window_mode", screen_mode)
	_config.set_value("settings", "master_volume", master_volume)
	_config.set_value("settings", "sounds_volume", sounds_volume)
	_config.set_value("settings", "music_volume", music_volume)

	_config.save(PATH)
	set_settings()


func set_settings() -> void:
	update_window_mode()
	AudioServer.set_bus_volume_linear(0, master_volume / 8.0)
	AudioServer.set_bus_volume_linear(1, sounds_volume / 8.0)
	AudioServer.set_bus_volume_linear(2, music_volume / 8.0)

func update_window_mode() -> void:
	match screen_mode:
		ScreenMode.FULLSCREEN:
			DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN)
		ScreenMode.WINDOWED:
			DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)
			DisplayServer.window_set_size(Vector2i(800, 720))
