74 lines
2.3 KiB
C#
74 lines
2.3 KiB
C#
using Chickensoft.Collections;
|
|
using Chickensoft.Serialization.Godot;
|
|
using Chickensoft.Serialization;
|
|
using Godot;
|
|
using System.IO.Abstractions;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization.Metadata;
|
|
using Zennysoft.Game.Abstractions;
|
|
|
|
namespace Zennysoft.Game.Ma.Implementation;
|
|
|
|
public class SaveFileManager<T> : ISaveFileManager<T>
|
|
{
|
|
private readonly IFileSystem _fileSystem;
|
|
private JsonSerializerOptions _jsonOptions;
|
|
private string _defaultSaveLocation;
|
|
public const string DEFAULT_SAVE_FILE_NAME = "game.json";
|
|
|
|
public SaveFileManager(IFileSystem fileSystem)
|
|
{
|
|
_fileSystem = fileSystem;
|
|
_defaultSaveLocation = _fileSystem.Path.Join(OS.GetUserDataDir(), DEFAULT_SAVE_FILE_NAME);
|
|
|
|
var resolver = new SerializableTypeResolver();
|
|
GodotSerialization.Setup();
|
|
Serializer.AddConverter(new Texture2DConverter());
|
|
|
|
var upgradeDependencies = new Blackboard();
|
|
|
|
_jsonOptions = new JsonSerializerOptions
|
|
{
|
|
Converters = {
|
|
new SerializableTypeConverter(upgradeDependencies)
|
|
},
|
|
TypeInfoResolver = JsonTypeInfoResolver.Combine(resolver, WeaponTagEnumContext.Default, ItemTagEnumContext.Default, ElementTypeEnumContext.Default, AccessoryTagEnumContext.Default, ThrowableItemTagEnumContext.Default, UsableItemTagEnumContext.Default, BoxItemTagEnumContext.Default),
|
|
WriteIndented = true
|
|
};
|
|
}
|
|
|
|
|
|
public Task<T?> ReadFromFile()
|
|
{
|
|
if (!_fileSystem.File.Exists(_defaultSaveLocation))
|
|
throw new FileNotFoundException();
|
|
return ReadFromFile(_defaultSaveLocation);
|
|
}
|
|
|
|
public async Task<T?> ReadFromFile(string filePath)
|
|
{
|
|
if (!_fileSystem.File.Exists(filePath))
|
|
throw new FileNotFoundException();
|
|
|
|
var json = await _fileSystem.File.ReadAllTextAsync(filePath);
|
|
|
|
return JsonSerializer.Deserialize<T?>(json, _jsonOptions);
|
|
}
|
|
|
|
public Task WriteToFile(T gameData)
|
|
{
|
|
return WriteToFile(gameData, _defaultSaveLocation, _jsonOptions);
|
|
}
|
|
|
|
public Task WriteToFile(T gameData, string filePath)
|
|
{
|
|
return WriteToFile(gameData, filePath, _jsonOptions);
|
|
}
|
|
|
|
public async Task WriteToFile(T gameData, string filePath, JsonSerializerOptions jsonOptions)
|
|
{
|
|
var json = JsonSerializer.Serialize(gameData, jsonOptions);
|
|
await _fileSystem.File.WriteAllTextAsync(filePath, json);
|
|
}
|
|
}
|