namespace SimpleCqrs
{
    using System;
    using System.Linq.Expressions;
    using System.Threading.Tasks;

    public static class DelegateAdjuster
    {
        public static Func<TBase, Task> CastArgument<TBase, TDerived>(Expression<Func<TDerived, Task>> source)
        {
            if (typeof(TDerived) == typeof(TBase))
            {
                return (Func<TBase, Task>)((Delegate)source.Compile());

            }
            ParameterExpression sourceParameter = Expression.Parameter(typeof(TBase), "source");
            var result = Expression.Lambda<Func<TBase, Task>>(
                Expression.Invoke(
                    source,
                    Expression.Convert(sourceParameter, typeof(TDerived))),
                sourceParameter);
            return result.Compile();
        }
    }
}