From 204db02cd9187561321db3b8d8ee2539ae9ea5da Mon Sep 17 00:00:00 2001
From: Toastie <toastie@toastiet0ast.com>
Date: Sun, 8 Dec 2024 15:53:59 +1300
Subject: [PATCH] Queueing a song after the queue is finished will restart the
 playback

---
 .../Modules/Music/_common/Impl/MusicPlayer.cs | 32 ++++++++++++++++---
 1 file changed, 27 insertions(+), 5 deletions(-)

diff --git a/src/EllieBot/Modules/Music/_common/Impl/MusicPlayer.cs b/src/EllieBot/Modules/Music/_common/Impl/MusicPlayer.cs
index 91178d3..65ef902 100644
--- a/src/EllieBot/Modules/Music/_common/Impl/MusicPlayer.cs
+++ b/src/EllieBot/Modules/Music/_common/Impl/MusicPlayer.cs
@@ -65,7 +65,17 @@ public sealed class MusicPlayer : IMusicPlayer
 
         _songBuffer = new PoopyBufferImmortalized(_vc.InputLength);
 
-        _thread = new(async () => { await PlayLoop(); });
+        _thread = new(async () =>
+        {
+            try
+            {
+                await PlayLoop();
+            }
+            catch (Exception ex)
+            {
+                Log.Error(ex, "Music player thread crashed");
+            }
+        });
         _thread.Start();
     }
 
@@ -402,12 +412,24 @@ public sealed class MusicPlayer : IMusicPlayer
         if (song is null)
             return default;
 
-        int index;
 
-        if (asNext)
-            return (_queue.EnqueueNext(song, queuer, out index), index);
+        var wasLast = _queue.IsLast();
 
-        return (_queue.Enqueue(song, queuer, out index), index);
+        try
+        {
+            int index;
+            if (asNext)
+                return (_queue.EnqueueNext(song, queuer, out index), index);
+
+            return (_queue.Enqueue(song, queuer, out index), index);
+        }
+        finally
+        {
+            // if (wasLast && IsStopped)
+            // {
+            //     IsStopped = false;
+            // }
+        }
     }
 
     public async Task EnqueueManyAsync(IEnumerable<(string Query, MusicPlatform Platform)> queries, string queuer)