using SharpPromise;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static LinqToDB.Reflection.Methods.LinqToDB.Insert;

namespace MasaBlazorApp3.Util
{
    public class PromiseUtil<T>
    {

        public int _delay { get; set; }

        public T? _data { get; set; }

        public async Task taskAsyncLoop(int delay, T data, Action<PromiseUtil<T>, Action, Action> action)
        {
            _data = data;
            _delay = 0;
            while (_delay >= 0)
            {
                await new Promise(async (Action onResolve, Action onReject) =>
                {
                    await Task.Delay(_delay);
                    try
                    {
                        await Task.Run(() => action(this, onResolve, onReject));
                    } catch (Exception ex)
                    {
                        onReject();
                    }
                }).Then(() =>
                {
                    _delay = delay;
                }).Catch((Exception e) =>
                {
                    _delay = -1;
                });
            }
        }
    }
}
