using System;
using Godot;
using Godot.Collections;
using FileAccess = Godot.FileAccess;
namespace Babushka.scripts.CSharp.Common.Savegame;
///
/// Handles the saving and loading of game states.
/// Holds the central SaveData object that serves as a temporary SaveFile.
/// Automatically writes to disk on every scene change.
///
public static class SavegameService
{
public static readonly string SavePath = "res://savegame/savegame.json";
public static Dictionary SaveDatas = new ();
public static bool _loaded = false;
///
/// Adds or overwrites an entry in the SaveData dictionary.
///
///
public static void AppendSave(SaveData saveData)
{
string key = string.Concat(saveData.SceneName, "_", saveData.Id);
if (SaveDatas.TryGetValue(key, out var value))
{
SaveDatas[key] = saveData.JsonPayload;
}
else
{
SaveDatas.Add(key, saveData.JsonPayload);
}
}
///
/// Checks the SaveData dictionary for an entry and returns the jsondata as a string for it.
/// Requires the scenename and object ID for lookup.
///
///
///
///
public static string GetSaveData(string sceneName, string id)
{
string saveData = "";
string key = string.Concat(sceneName, "_", id);
if (!_loaded)
{
GD.Print("SavegameService: SaveFile not loaded.");
return saveData;
}
if (SaveDatas.ContainsKey(key))
{
saveData = SaveDatas[key];
}
return saveData;
}
///
/// Writes the contents of the current SaveData dictionary to disk as a json file.
///
public static void Save()
{
string json = Json.Stringify(SaveDatas, indent: "\t");
using var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Write);
file.StoreString(json);
}
///
/// Loads the current savegame file from disk and parses it into the SaveData dictionary.
///
public static void Load()
{
try
{
string saveDataJson = FileAccess.GetFileAsString(SavePath);
SaveDatas = Json.ParseString(saveDataJson).AsGodotDictionary();
}
catch(Exception e)
{
GD.PrintRich(e.Message);
return;
}
_loaded = true;
}
}