PkmnLib.NET/PkmnLib.Dataloader/ItemDataLoader.cs

46 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json;
using PkmnLib.Dataloader.Models;
using PkmnLib.Static;
using PkmnLib.Static.Libraries;
using PkmnLib.Static.Utils;
namespace PkmnLib.Dataloader;
public static class ItemDataLoader
{
public static ItemLibrary LoadItems(Stream stream)
{
var library = new ItemLibrary();
var obj = JsonSerializer.Deserialize<SerializedItem[]>(stream, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
});
if (obj == null)
throw new InvalidDataException("Item data is empty.");
var items = obj.Select(DeserializeItem);
foreach (var i in items)
library.Add(i);
return library;
}
public static Func<SerializedItem, StringKey, ItemCategory, BattleItemCategory, int,
IEnumerable<StringKey>, IItem> ItemConstructor = (_, name, type, battleType, price, flags) =>
{
return new ItemImpl(name, type, battleType, price, flags);
};
private static IItem DeserializeItem(SerializedItem serialized)
{
if (!Enum.TryParse<ItemCategory>(serialized.ItemType, true, out var itemType))
throw new InvalidDataException($"Item type {serialized.ItemType} is not valid for item {serialized.Name}.");
Enum.TryParse(serialized.BattleType, true, out BattleItemCategory battleType);
return ItemConstructor(serialized, serialized.Name, itemType, battleType, serialized.Price,
serialized.Flags.Select(x => (StringKey)x).ToImmutableHashSet());
}
}