//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// UserRTX.NET satellite library | Author: Sergei Y.Kitáev
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Threading.Tasks;

#if !WASM
namespace user_rtx { using u = user_rtx;
#else
namespace user_rtx.wasm { using u = user_rtx.wasm;
#endif

static partial class task {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/// <exception cref="ETaskInvocation" />
public static void SyncDo( Func<Task> actionA ) =>
   SyncDo( true, actionA );
/// <exception cref="ETaskInvocation" />
/// <exception cref="Exception" />
public static void SyncDo( [u.DefTrue] bool wrapException, Func<Task> actionA )
{
   Exception? error = SyncCatch( actionA );
   if ( error != null )
      throw wrapException ? new ETaskInvocation( error ) : error;
}

//--------------------------------------------------------------------------------------------------

/// <exception cref="ETaskInvocation" />
public static R SyncDo<R>( Func<Task<R>> functionA ) =>
   SyncDo<R>( true, functionA );
/// <exception cref="ETaskInvocation" />
/// <exception cref="Exception" />
public static R SyncDo<R>( [u.DefTrue] bool wrapException, Func<Task<R>> functionA )
{
   R? result;
   Exception? error = SyncCatch<R>( out result, functionA );
   if ( error != null )
      throw wrapException ? new ETaskInvocation( error ) : error;
   u.assertion.Verify( result != null );
   return result!;
}

//==================================================================================================

public static Exception? SyncCatch( Func<Task> actionA ) =>
   Task<Exception?>.Run(() => u.ops.Catch_A( actionA )).Result;

public static Exception? SyncCatch<R>( out R? result, Func<Task<R>> functionA )
{
   var (e,r) = Task<(Exception?,R?)>.Run(() => u.ops.Catch_A<R>( functionA )).Result;
   result = r;
   return e;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // task

} // user_rtx (.wasm)
