using System; using System.Collections.Generic; using System.IO; using IronMountain.SaveSystem; namespace SpellBoundAR.Items.Inventories { public class SavedInventory : IInventory { public event Action OnEntriesChanged; private string _directory = string.Empty; public string ID { get; } public string Directory { get => _directory; set { if (_directory == value) return; _directory = value; ReloadEntries(); } } private readonly List _entries = new (); public List GetAllEntries() => _entries; public IInventoryEntry GetEntry(IItemTypeData itemTypeData) { if (itemTypeData == null) return null; foreach (IInventoryEntry entry in _entries) { if (entry?.ItemTypeData == null) continue; if (entry.ItemTypeData == itemTypeData || entry.ItemTypeData.ID == itemTypeData.ID) return entry; } return null; } public virtual void Add(IItemTypeData itemTypeData, int quantity) { if (itemTypeData == null) return; IInventoryEntry entry = GetEntry(itemTypeData); if (entry == null) { _entries.Add(new SavedInventoryEntry( Path.Combine(Directory, Guid.NewGuid().ToString()), itemTypeData, quantity, 0 )); OnEntriesChanged?.Invoke(); } else entry.Quantity += quantity; IInventory.InvokeOnAnyInventoryChanged(this, itemTypeData); } public virtual void Remove(IItemTypeData itemTypeData, int amount) { if (itemTypeData == null) return; IInventoryEntry entry = GetEntry(itemTypeData); if (entry == null) return; entry.Quantity -= amount; if (entry.Quantity == 0 && entry is SavedInventoryEntry savedInventoryEntry) { _entries.Remove(entry); SaveSystem.DeleteDirectory(savedInventoryEntry.Directory); OnEntriesChanged?.Invoke(); } IInventory.InvokeOnAnyInventoryChanged(this, itemTypeData); } public virtual void RemoveAll(IItemTypeData itemTypeData) { if (itemTypeData == null) return; IInventoryEntry entry = GetEntry(itemTypeData); if (entry == null) return; entry.Quantity = 0; _entries.Remove(entry); if (entry is SavedInventoryEntry savedInventoryEntry) { SaveSystem.DeleteDirectory(savedInventoryEntry.Directory); } OnEntriesChanged?.Invoke(); IInventory.InvokeOnAnyInventoryChanged(this, itemTypeData); } public virtual void Clear() { _entries.Clear(); DirectoryInfo[] directoryList = SaveSystem.GetDirectoryInfo(Directory); foreach (DirectoryInfo directoryInfo in directoryList) { string entryPath = Path.Combine(Directory, directoryInfo.Name); SaveSystem.DeleteDirectory(entryPath); } OnEntriesChanged?.Invoke(); } private void ReloadEntries() { _entries.Clear(); DirectoryInfo[] directoryList = SaveSystem.GetDirectoryInfo(Directory); foreach (DirectoryInfo directoryInfo in directoryList) { string entryPath = Path.Combine(Directory, directoryInfo.Name); _entries.Add(new SavedInventoryEntry(entryPath)); } OnEntriesChanged?.Invoke(); } public SavedInventory(string directory, string id) { Directory = directory; ID = id; ReloadEntries(); } } }