using System; using System.Collections.Generic; using YachtDice.Modifiers; namespace YachtDice.Inventory { public sealed class InventoryModel { private readonly List ownedModifiers = new(); private int maxActiveSlots; public IReadOnlyList OwnedModifiers => ownedModifiers; public int MaxActiveSlots => maxActiveSlots; public event Action OnInventoryChanged; public event Action> OnActiveModifiersChanged; public InventoryModel(int maxActiveSlots = 5) { this.maxActiveSlots = maxActiveSlots; } public int ActiveCount { get { int count = 0; for (int i = 0; i < ownedModifiers.Count; i++) if (ownedModifiers[i].IsActive) count++; return count; } } public void SetMaxActiveSlots(int slots) { maxActiveSlots = slots; } public void AddModifier(ModifierData data) { var runtime = ModifierRuntime.Create(data); ownedModifiers.Add(runtime); OnInventoryChanged?.Invoke(); } public void RemoveModifier(ModifierRuntime modifier) { if (!ownedModifiers.Contains(modifier)) return; if (modifier.IsActive) { modifier.IsActive = false; OnActiveModifiersChanged?.Invoke(GetActiveModifierData()); } ownedModifiers.Remove(modifier); OnInventoryChanged?.Invoke(); } public bool TryActivate(ModifierRuntime modifier) { if (modifier.IsActive) return false; if (!ownedModifiers.Contains(modifier)) return false; if (ActiveCount >= maxActiveSlots) return false; modifier.IsActive = true; OnActiveModifiersChanged?.Invoke(GetActiveModifierData()); OnInventoryChanged?.Invoke(); return true; } public void Deactivate(ModifierRuntime modifier) { if (!modifier.IsActive) return; modifier.IsActive = false; OnActiveModifiersChanged?.Invoke(GetActiveModifierData()); OnInventoryChanged?.Invoke(); } public void ConsumeUseOnActive() { bool changed = false; for (int i = ownedModifiers.Count - 1; i >= 0; i--) { var mod = ownedModifiers[i]; if (!mod.IsActive) continue; if (mod.Data == null) continue; if (mod.Data.Durability != ModifierDurability.LimitedUses) continue; mod.ConsumeUse(); if (mod.IsExpired) { ownedModifiers.RemoveAt(i); changed = true; } } if (changed) { OnActiveModifiersChanged?.Invoke(GetActiveModifierData()); OnInventoryChanged?.Invoke(); } } public List GetActiveModifierData() { var result = new List(); for (int i = 0; i < ownedModifiers.Count; i++) { if (ownedModifiers[i].IsActive && ownedModifiers[i].Data != null) result.Add(ownedModifiers[i].Data); } return result; } public void LoadState(List loaded) { ownedModifiers.Clear(); if (loaded != null) ownedModifiers.AddRange(loaded); OnActiveModifiersChanged?.Invoke(GetActiveModifierData()); OnInventoryChanged?.Invoke(); } public List GetAllForSave() => new(ownedModifiers); } }