using System.Globalization; namespace StateLab.Services; public sealed record Product(string Name, decimal PriceEur); public sealed record CartLine(Product Product, int Quantity) { public decimal TotalEur => Product.PriceEur * Quantity; } // The cascading value. Prices are stored in euros and converted for display. public sealed record Currency(string Code, string Symbol, decimal PerEuro) { public static readonly Currency Euro = new("EUR", "€", 1.00m); public static readonly Currency Dollar = new("USD", "$", 1.10m); // a fixed demo rate public string Format(decimal euros) => Symbol + (euros * PerEuro).ToString("0.00", CultureInfo.InvariantCulture); } // A state container: it holds the data and raises OnChange after every change. // It knows nothing about components; they subscribe to the event. public sealed class CartState { private readonly List lines = []; private Timer? giftTimer; public event Action? OnChange; public IReadOnlyList Lines => lines; public int Count => lines.Sum(line => line.Quantity); public decimal TotalEur => lines.Sum(line => line.TotalEur); public bool GiftPending => giftTimer is not null; public void Add(Product product) { var index = lines.FindIndex(line => line.Product == product); if (index >= 0) { lines[index] = lines[index] with { Quantity = lines[index].Quantity + 1 }; } else { lines.Add(new CartLine(product, 1)); } NotifyStateChanged(); } public void Remove(CartLine line) { lines.Remove(line); NotifyStateChanged(); } public void Clear() { lines.Clear(); NotifyStateChanged(); } // Adds a gift later from a timer callback. The change does not come from a // click in any component, like a message from a server would not. public void ScheduleGift(TimeSpan delay) { if (giftTimer is not null) return; giftTimer = new Timer(_ => { giftTimer?.Dispose(); giftTimer = null; Add(new Product("Sticker (gift)", 0m)); }, null, delay, Timeout.InfiniteTimeSpan); NotifyStateChanged(); } private void NotifyStateChanged() => OnChange?.Invoke(); }