extends Node

const SAVEFILE = "res://SAVEFILE.save"

var game_data = {}

func _ready() -> void:
	load_data()
	apply_settings()

func load_data() -> void:
	if not FileAccess.file_exists(SAVEFILE):
		# Create default data if the save file doesn't exist
		game_data = {
			"volume": 50,
			"music": 100,
			"sfx": 100,
			"mute": false,
			"resolution": 2,
			"fullscreen": false
		}
		save_data()
	else:
		var file = FileAccess.open(SAVEFILE, FileAccess.READ)
		if file:
			var json_data = file.get_as_text()
			file.close()

			# Create an instance of JSON
			var json = JSON.new()
			# Parse JSON data
			var error = json.parse(json_data)
			if error == OK:
				game_data = json.get_data()
			else:
				print("Error parsing save file: ", json.get_error_message())
				# Fallback to default data if parsing fails
				game_data = {
					"volume": 50,
					"music": 100,
					"sfx": 100,
					"mute": false,
					"resolution": 2,
					"fullscreen": false
				}
		else:
			print("Error opening save file.")
			# Fallback to default data if file cannot be opened
			game_data = {
				"volume": 50,
				"music": 100,
				"sfx": 100,
				"mute": false,
				"resolution": 2,
				"fullscreen": false
			}

func save_data() -> void:
	var file = FileAccess.open(SAVEFILE, FileAccess.WRITE)
	if file:
		# Create an instance of JSON
		var json = JSON.new()
		# Convert game_data to JSON string
		var json_data = json.stringify(game_data)
		file.store_string(json_data)
		file.close()
	else:
		print("Error saving data to file.")

func apply_settings() -> void:
	if game_data.has("volume"):
		GlobalSettings.volume_value_changed(game_data.volume)
	if game_data.has("music"):
		GlobalSettings.music_value_changed(game_data.volume)
	if game_data.has("sfx"):
		GlobalSettings.sfx_value_changed(game_data.sfx)
	if game_data.has("mute"):
		GlobalSettings.mute_toggled(game_data.mute)
	if game_data.has("resolution"):
		GlobalSettings.resolution_item_selected(game_data.resolution)
	if game_data.has("fullscreen"):
		GlobalSettings.toggle_fullscreen(game_data.fullscreen)
