Move runtime item references to typed keys
This commit is contained in:
parent
399efc3851
commit
8337d5f5c7
9 changed files with 153 additions and 60 deletions
|
|
@ -5,25 +5,62 @@ using GameCult.Aetheria.State.Unity;
|
|||
|
||||
public interface IRuntimeItemCatalogReader
|
||||
{
|
||||
AetheriaRuntimeCatalogItem GetRuntimeItem(string itemKey);
|
||||
AetheriaRuntimeCatalogItem GetRuntimeItem(Guid guid);
|
||||
}
|
||||
|
||||
public sealed class AetheriaRuntimeItemCatalog : IRuntimeItemCatalogReader
|
||||
{
|
||||
private readonly Dictionary<Guid, AetheriaRuntimeCatalogItem> _typedItems;
|
||||
private const string ItemDefinitionPrefix = "aetheria.item_definition:";
|
||||
private const string LegacyItemDefinitionPrefix = "aetheria.item_definition:legacy:";
|
||||
|
||||
private readonly Dictionary<string, AetheriaRuntimeCatalogItem> _typedItemsByKey;
|
||||
private readonly Dictionary<Guid, AetheriaRuntimeCatalogItem> _typedItemsByLegacyId;
|
||||
|
||||
public AetheriaRuntimeItemCatalog(AetheriaRuntimeCatalogSnapshot catalog)
|
||||
{
|
||||
if (catalog == null) throw new ArgumentNullException(nameof(catalog));
|
||||
|
||||
_typedItems = catalog.Items
|
||||
_typedItemsByKey = catalog.Items
|
||||
.Where(item => !string.IsNullOrWhiteSpace(item.LegacyId))
|
||||
.ToDictionary(item => ToItemKey(item.LegacyId), item => item, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
_typedItemsByLegacyId = catalog.Items
|
||||
.Where(item => Guid.TryParse(item.LegacyId, out _))
|
||||
.ToDictionary(item => Guid.Parse(item.LegacyId), item => item);
|
||||
}
|
||||
|
||||
public AetheriaRuntimeCatalogItem GetRuntimeItem(string itemKey)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(itemKey))
|
||||
return null;
|
||||
|
||||
if (_typedItemsByKey.TryGetValue(itemKey, out var item))
|
||||
return item;
|
||||
|
||||
return Guid.TryParse(RemoveItemPrefix(itemKey), out var legacyId)
|
||||
? GetRuntimeItem(legacyId)
|
||||
: null;
|
||||
}
|
||||
|
||||
public AetheriaRuntimeCatalogItem GetRuntimeItem(Guid guid)
|
||||
{
|
||||
_typedItems.TryGetValue(guid, out var item);
|
||||
_typedItemsByLegacyId.TryGetValue(guid, out var item);
|
||||
return item;
|
||||
}
|
||||
|
||||
private static string ToItemKey(string legacyId)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(legacyId) ? "" : $"{LegacyItemDefinitionPrefix}{legacyId}";
|
||||
}
|
||||
|
||||
private static string RemoveItemPrefix(string itemKey)
|
||||
{
|
||||
if (itemKey.StartsWith(LegacyItemDefinitionPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
return itemKey.Substring(LegacyItemDefinitionPrefix.Length);
|
||||
|
||||
return itemKey.StartsWith(ItemDefinitionPrefix, StringComparison.OrdinalIgnoreCase)
|
||||
? itemKey.Substring(ItemDefinitionPrefix.Length)
|
||||
: itemKey;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue