# Hurry Curry! - a game about cooking
# Copyright (C) 2026 Hurry Curry! Contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
extends Node
class_name Profile

static var default_profile := {
	"username": "",
	"character_style": {
		"color": 0,
		"headwear": 0,
		"hairstyle": 0
	},
	"last_server_url": "",
	"tutorial_ingredients_played": [],
	"registry_asked": false,
	"controls_keyboard_one_handed_explained": false,
	"controls_keyboard_two_handed_explained": false,
	"controls_joypad_one_handed_explained": false,
	"controls_joypad_two_handed_explained": false
}

# profile is stored in a Dictionary[String, Any]
static var values: Dictionary
static var loaded_path: String

static func load(path: String):
	# TOCTOU here. Godot docs says its fine.
	print("Loading profile from %s" % path)
	if not FileAccess.file_exists(path):
		print(" -> using default profile")
		values = default_profile.duplicate_deep()
		loaded_path = path
		return
	var f = FileAccess.open(path, FileAccess.READ)

	values = f.get_var(true)
	loaded_path = path
	if values != null and values is Dictionary:
		G.add_missing_keys(values, default_profile)

static func save():
	DirAccess.make_dir_recursive_absolute(loaded_path.rsplit("/", true, 1)[0])
	var f = FileAccess.open(loaded_path, FileAccess.WRITE)
	var to_save = values.duplicate(true)
	f.store_var(to_save, true)

static func read(key: String):
	if values.has(key):
		return values[key]
	else:
		push_error("Tried to access profile setting \"%s\", which does not exist (missing key)" % key)
		return null

static func write(key: String, value: Variant, autosave := true):
	if !values.has(key):
		push_error("Tried to set profile setting \"%s\", which does not yet exist (missing key)" % key)
		return
	if values[key] != value:
		values[key] = value
	if autosave:
		save()
