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

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

/// <summary>
/// COM-error helpers (Component Object Model)
/// </summary>
public static partial class com_error {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public static string HRToMessage( int errorCode ) =>
   HRToMessage( errorCode, u.iptr.Minus1Value );

public static string HRToMessage( int errorCode, [u.opt] IntPtr errorInfo )
{
   Exception? e = Marshal.GetExceptionForHR( errorCode, errorInfo );
   return e != null ? e.Message :
      "Undefined COM-error.";
}

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

public static string ErrorMessageFor( string functionName ) =>
   ErrorMessageFor( functionName, null );

public static string ErrorMessageFor( string functionName, string? remarkMessage ) =>
   u.str.FMT(
      "COM-function “{0}” has failed.{1}", functionName,
      remarkMessage!=null ? $"\n({remarkMessage})" : "" );

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

public static string ErrorMessageWithReturnCodeToken( string functionName,
                                                      string returnCodeToken ) =>
   ErrorMessageFor( functionName,
      $"COM Return Code = {returnCodeToken}" );

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

public static string ErrorMessage_CantObtainInterface( string interfaceName, int hResult ) =>
   u.str.FMT(
      "Can not obtain “{0}” COM-interface.\n"+
      "{1}.", interfaceName, HRToMessage( hResult ) );

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // com_error

} // user_rtx (.wasm)
