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

namespace SortVisualizer;

public class InsertionSort : ISortAlgorithm
{
    public string Name => "Insertion Sort";

    public async Task Sort(int[] array, Action refresh, int delay, Action<int> playSound, CancellationToken token)
    {
        for (int i = 1; i < array.Length; i++)
        {
            if (token.IsCancellationRequested) return;

            int key = array[i];
            int j = i - 1;

            while (j >= 0 && array[j] > key)
            {
                if (token.IsCancellationRequested) return;

                playSound(array[j]);
                array[j + 1] = array[j];
                j--;
                refresh();
                await Task.Delay(delay);
            }
            array[j + 1] = key;
        }
    }
}
