﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.VisualStudio.TestTools.UnitTesting
{

    [System.Diagnostics.DebuggerStepThroughAttribute()] 
    public static class ChainingAssertionExtension
    {
        public static void IsAsync<T>(this T actual, Predicate<T> predicate, string message = "", int retryCount = 10, TaskCompletionSource<bool> source = null)
        {
            IsTaskAsync(actual, predicate, message, retryCount, source).Result.IsTrue();
        }

        public static Task<bool> IsTaskAsync<T>(this T actual, Predicate<T> predicate, string message = "", int retryCount = 10, TaskCompletionSource<bool> source = null)
        {
            if (source == null)
            {
                source = new TaskCompletionSource<bool>();
            }
            if (predicate(actual))
            {
                source.SetResult(true);
            }
            else if (retryCount != 0)
            {
                Task.Delay(500).ContinueWith((task) =>
                {
                    actual.IsTaskAsync(predicate, message, retryCount - 1, source);
                });
            }
            else
            {
                source.SetResult(false);
            }
            return source.Task;
        }
    }
}
