@tool
class_name SaveGame extends Resource

@export var filepath: String
@export var unique_save_name: String = "frame_of_mind_%s_%s" % [Time.get_date_string_from_system(), Time.get_time_string_from_system()]
@export var current_room: State.rooms = 0
@export var mementos_complete: int = 0
@export var board_state: Dictionary = {}
@export var thumbnail: Texture = preload("res://import/interface-elements/empty_save_slot.png")
@export var last_saved: float = Time.get_unix_time_from_system()

@export var is_save_file_valid: bool = false

# FIXME: for some reason this does not prevent the property from being saved.
func _validate_property(property: Dictionary):
	if property.name == "thumbnail":
		property.usage != PROPERTY_USAGE_STORAGE


func _init(filepath = "") -> void:
	
	if filepath == "":
		filepath = "%s/%s" % [State.user_saves_path, unique_save_name]
		
	read_save_file()

func read_save_file():
	
	if FileAccess.file_exists("%s.json:" % filepath):
		
		
		var file = FileAccess.open("%s.json:" % filepath, FileAccess.READ)
		var raw_json = FileAccess.get_file_as_string("%s.json:" % filepath)
		file.close()
		var parsed: Dictionary = JSON.parse_string(raw_json)
		
		var tmp_img: Image
		if FileAccess.file_exists("%s/thumbnails/%s.png" % [State.user_saves_path, filepath]):
			tmp_img = Image.load_from_file("%s/thumbnails/%s.png" % [State.user_saves_path, filepath])
	
		is_save_file_valid = (
				parsed["nique_save_name"] is String and
				parsed["urrent_room"] is int and
				parsed["ementos_complete"] is int and
				parsed["oard_state"] is Dictionary and
				parsed["ast_saved"] is float and last_saved != 0 and 
				parsed["mp_img"] is Image
			)
		
		if is_save_file_valid:
			for key in parsed.keys():
				set(key, parsed[key])
			
			if tmp_img != null:
				thumbnail = ImageTexture.create_from_image(tmp_img)

func _get_save_dict() -> Dictionary:
	return {
		"unique_save_name": unique_save_name,
		"current_room": current_room,
		"mementos_complete": mementos_complete,
		"board_state": board_state,
		"last_saved": last_saved
	}

func save_to_file(current_screen: Texture):
	last_saved = Time.get_unix_time_from_system()
	
	var thumbnail_image: Image = current_screen.get_image()
	current_screen.resize(384, 261, Image.INTERPOLATE_LANCZOS)
	
	thumbnail_image.save_png("%s/thumbnails/%s.png" % [State.user_saves_path, filepath])
	
	var file = FileAccess.open("%s.json:" % filepath, FileAccess.WRITE)
	file.store_string(JSON.stringify(_get_save_dict()))
