extends Node

const FILE_PATH = "user://local_storage"



func _ready():
	apply_settings()


func apply_settings():
	apply_locale()
	apply_game_server()
	apply_resolution()
	apply_controls()


func apply_locale():
	TranslationServer.set_locale(config.get_value("system","locale","en"))


func apply_game_server():
	var server_addr = config.get_value("system", "server_addr")
	if server_addr != null && not server_addr.empty():
		game_server.set_server_addr(server_addr)
	var api_addr = config.get_value("system","api_addr")
	if api_addr != null && not api_addr.empty():
		game_server.set_api_addr(api_addr)


func apply_resolution():
	var view_port = get_tree().get_root()
	OS.set_window_fullscreen(config.get_value("graphics","fullscreen", true))

	var resolution = config.get_value("graphics","resolution",config.RESOLUTIONS[0])
	if OS.is_window_fullscreen():
		var base_size = Vector2(1920, 1080)
		var scale= base_size.x / resolution.x
		get_tree().set_screen_stretch(SceneTree.STRETCH_MODE_2D,SceneTree.STRETCH_ASPECT_EXPAND,base_size,scale)
	else:
		OS.set_window_size(resolution)
		OS.set_window_position(Vector2((OS.get_screen_size().x - resolution.x) / 2, (OS.get_screen_size().y - resolution.y) / 2)) # center screen
		get_tree().set_screen_stretch(SceneTree.STRETCH_MODE_VIEWPORT,SceneTree.STRETCH_ASPECT_IGNORE,OS.get_window_size(),1)


func apply_controls():
	InputMap.load_from_globals()
	var control_map = config.get_value("controls","mapping",{})
	for action in InputMap.get_actions():
		if control_map.has(action):
			for event in InputMap.get_action_list(action):
				if event is InputEventKey && control_map[action].has("key"):
					InputMap.action_erase_event(action, event)
					event.set_scancode(OS.find_scancode_from_string(control_map[action]["key"]))
					InputMap.action_add_event(action,event)
				elif event is InputEventJoypadButton && control_map[action].has("joypad"):
					InputMap.action_erase_event(action, event)
					event.set_button_index(control_map[action]["joypad"])
					InputMap.action_add_event(action,event)

	for ui_mapping in config.INPUT_UI_MAPPING:
		for event in InputMap.get_action_list(config.INPUT_UI_MAPPING[ui_mapping]):
			InputMap.action_add_event(ui_mapping, event)