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

namespace UVC.Util
{
    public class Debounce : IDisposable
    {
        private CancellationTokenSource cts = new CancellationTokenSource();

        /// <summary>
        /// 마지막 호출 된 함수 한번 실행. milliseconds 이후 실행 되어 추가로 호추 되면 이전 함수 취소 함.
        /// Debounce debounce = new Debounce();
        /// debounce.DebounceAction(1000, repository.SaveToolBarData, data);
        /// </summary>
        /// <typeparam name="T">param Type</typeparam>
        /// <param name="milliseconds"></param>
        /// <param name="action"></param>
        /// <param name="param"></param>
        public void DebounceAction<T>(int milliseconds, Action<T> action, T param)
        {
            resetCancellationToken();
            UniTask.Delay(TimeSpan.FromMilliseconds(milliseconds), cancellationToken: cts.Token, ignoreTimeScale: false).ContinueWith(() =>
            {
                action.Invoke(param);
            });
        }

        /// <summary>
        /// 마지막 호출 된 함수 한번 실행. milliseconds 이후 실행 되어 추가로 호추 되면 이전 함수 취소 함.
        /// Debounce debounce = new Debounce();
        /// debounce.DebounceUniTask(1000, repository.SaveToolBarData, data);
        /// </summary>
        /// <typeparam name="T">param Type</typeparam>
        /// <param name="milliseconds"></param>
        /// <param name="action"></param>
        /// <param name="param"></param>
        public void DebounceUniTask<T>(int milliseconds, Func<T, UniTaskVoid> action, T param)
        {
            resetCancellationToken();
            UniTask.Delay(TimeSpan.FromMilliseconds(milliseconds), cancellationToken: cts.Token, ignoreTimeScale: false).ContinueWith(() =>
            {
                action.Invoke(param).Forget();
            });
        }



        private void resetCancellationToken()
        {
            cts.Cancel();
            cts = new CancellationTokenSource();
        }


        public void Dispose()
        {
            cts.Cancel();
            cts.Dispose();
        }

    }
}
