namespace EvilEngine.Music.Playback; public enum RepeatMode { Off, All, One } public sealed class PlayQueue(Random? random = null) { public const double RestartAfterSeconds = 3; private readonly Random random = random ?? Random.Shared; private List items = []; private List order = []; private int position = -1; private bool shuffle; public IReadOnlyList Items => items; public RepeatMode Repeat { get; set; } public string? Current => position >= 0 && position < order.Count ? items[order[position]] : null; public IEnumerable Upcoming => order.Skip(position + 1).Select(index => items[index]); public bool Shuffle { get => shuffle; set { if (shuffle == value) return; shuffle = value; var current = position >= 0 && position < order.Count ? order[position] : -1; Order(current); } } public string? Play(IReadOnlyList list, int start) { items = [.. list]; if (items.Count == 0) { order = []; position = -1; return null; } Order(Math.Clamp(start, 0, items.Count - 1)); return Current; } public string? Next(bool ended) { if (order.Count == 0) return null; if (ended && Repeat == RepeatMode.One) return Current; if (position + 1 < order.Count) { position++; return Current; } if (Repeat == RepeatMode.Off) { if (ended) position = order.Count; return null; } if (shuffle) Order(-1); position = 0; return Current; } public string? Previous(double seconds) { if (order.Count == 0) return null; if (seconds > RestartAfterSeconds || (position <= 0 && Repeat != RepeatMode.All)) { position = Math.Clamp(position, 0, order.Count - 1); return Current; } position = position <= 0 ? order.Count - 1 : position - 1; return Current; } public void Clear() { items = []; order = []; position = -1; } private void Order(int current) { order = Enumerable.Range(0, items.Count).ToList(); if (!shuffle) { position = current; return; } if (current >= 0) order.Remove(current); for (var i = order.Count - 1; i > 0; i--) { var j = random.Next(i + 1); (order[i], order[j]) = (order[j], order[i]); } if (current >= 0) order.Insert(0, current); position = current >= 0 ? 0 : -1; } }