using System;
using System.Threading;
using System.Threading.Tasks;

namespace SortVisualizer;

public class BogoSort : ISortAlgorithm
{
    public string Name => "Bogo Sort";

    private static readonly Random rand = new();
    public static BogoSort Instance { get; } = new BogoSort();
    public BogoSort() { }

    public async Task Sort(int[] array, Action refresh, int delay, Action<int> playSound, CancellationToken token)
    {
        try
        {
            while (!IsSorted(array))
            {
                token.ThrowIfCancellationRequested();

                // Shuffle array
                for (int i = 0; i < array.Length; i++)
                {
                    int j = rand.Next(array.Length);
                    (array[i], array[j]) = (array[j], array[i]);

                    playSound?.Invoke(array[i]);
                    refresh?.Invoke();

                    // small delay for live updates
                    await Task.Delay(delay, token);
                }
            }
        }
        catch (TaskCanceledException)
        {
            // Sorting was stopped; exit gracefully
        }
    }

    private bool IsSorted(int[] array)
    {
        for (int i = 1; i < array.Length; i++)
            if (array[i - 1] > array[i])
                return false;
        return true;
    }
}
