// RuntimeForStatic base library | C+- (SysRoutine) | Author: Sergei Y.Kitáev
#include "Precompiled.h"
#include "SharedIncludes.h"
namespace RuntimeForStatic {
//==================================================================================================

$AutoHandles::$AutoHandles($A, const std::initializer_list<HANDLE volatile*>& handlePointers )
: $AutoHandles($ci, false, handlePointers )
{}
$AutoHandles::$AutoHandles($A, bool isOfInvalidHandleValueCategory,
                               const std::initializer_list<HANDLE volatile*>& handlePointers )
{
   for (auto pHandle: handlePointers)
      $$VERIFY_POINTER_ARG( pHandle );
   _HandlePointers_ = handlePointers;
   _IsOfInvalidHandleValueCategory_ = isOfInvalidHandleValueCategory;
   ValidateDisposable($$);
}

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

void $AutoHandles::DoDispose($CI_REF)
{
   Close($ci);
}

void $AutoHandles::ResetSuperstructure()
{
   _HandlePointers_ = std::initializer_list<HANDLE volatile*>();
   _IsOfInvalidHandleValueCategory_ = false;
}

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

bool $AutoHandles::Close($O) $last_system_error
{
   if ( !IsValidDisposable )
      return $Win32Error::ResetLastSysError();
   $$VERIFY_VALID_DISPOSABLE();
   auto handlePointers = _HandlePointers_;
   bool isOfInvalidHandleValueCategory = _IsOfInvalidHandleValueCategory_;
   ResetSuperstructure();
   InvalidateDisposable();
   DWORD dwError = 0;
   for (auto pHandle: handlePointers)
   {
      HANDLE handle = $Handle::Exchange($, pHandle,
         isOfInvalidHandleValueCategory ? INVALID_HANDLE_VALUE : nullptr );
      if ( $Handle::IsValid( handle, isOfInvalidHandleValueCategory ) )
      {
         ::CloseHandle( handle );
         $subst::ReplaceNull( dwError, ::GetLastError() );
      }
   }
   ::SetLastError( dwError );
   return $BOOL( dwError );
}

//==================================================================================================
} // RuntimeForStatic
