#include <WinTen.h>
#include <Windows.h>
#include <ClipApi.h>
#include <Mapi.h>

#define MAPI_LOGOFF_SHARED    1
#define MAPI_LOGOFF_UI        2

#define MAPI_ALLOW_OTHERS     8

static ULONG ulMailHandle;

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

CLIPPER MAPILOGON() // ( [ cUserName ], [ cPassword ] )  --> lResult
{
   LPSTR szUserName = IF( PCOUNT() == 1, _parc( 1 ), NULL );
   LPSTR szPassword = IF( PCOUNT() == 2, _parc( 2 ), NULL );

   _retl( MAPILogon( GetActiveWindow(), szUserName, szPassword,
                     MAPI_LOGON_UI | MAPI_FORCE_DOWNLOAD | MAPI_ALLOW_OTHERS,
                     0, &ulMailHandle ) );
}

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

CLIPPER MAPILOGOFF()
{
   if( ulMailHandle )
   {
      _retl( MAPILogoff( ulMailHandle, GetActiveWindow(),
                         MAPI_LOGOFF_SHARED | MAPI_LOGOFF_UI, 0 ) );
      ulMailHandle = 0;
   }
   else
      MessageBox( GetActiveWindow(), "No MAIL session was active",
                  "Attention", MB_ICONEXCLAMATION );
}

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

CLIPPER MAPISENDMA()
{
   MapiMessage msg;
   MapiRecipDesc origin;
   MapiRecipDesc target[ 10 ];
   WORD w, wLen;

   _bset( ( LPBYTE ) &msg,    0, sizeof( msg ) );
   _bset( ( LPBYTE ) &origin, 0, sizeof( origin ) );
   _bset( ( LPBYTE ) target,  0, sizeof( target ) );

   msg.ulReserved         = 0;
   msg.lpszSubject        = IF( ISCHAR( 1 ), _parc( 1 ), NULL );
   msg.lpszNoteText       = IF( ISCHAR( 2 ), _parc( 2 ), NULL );
   // msg.lpszMessageType    = IF( ISCHAR( 3 ), _parc( 3 ), NULL );
   msg.lpszDateReceived   = IF( ISCHAR( 4 ), _parc( 4 ), NULL );
   // msg.lpszConversationID = IF( ISCHAR( 5 ), _parc( 5 ), NULL );
   msg.flFlags            = IF( ( ISLOGICAL( 6 ) && _parl( 6 ) ),
                                MAPI_RECEIPT_REQUESTED, 0 );

   if( ISARRAY( 8 ) && _VARRAYLEN( _param( 8, ARRAY ) ) )
   {
      origin.lpszName    = _parc( 8, 1 );
      origin.lpszAddress = _parc( 8, 2 );
      msg.lpOriginator   = &origin;
   }

   if( ISARRAY( 9 ) && ( wLen = _VARRAYLEN( _param( 9, ARRAY ) ) ) )
   {
      for( w = 0; w < wLen; w++ )
      {
         _cAt( _param( 9, ARRAY ), w + 1, -1, _eval );
         target[ w ].lpszName    = _parc( -1, 1 );
         target[ w ].lpszAddress = _parc( -1, 2 );
      }
      msg.nRecipCount = wLen;
      msg.lpRecips    = target;
   }

   if( ulMailHandle )
   {
      _retnl( MAPISendMail( ulMailHandle, GetActiveWindow(), &msg,
                            IF( ( ISLOGICAL( 7 ) && _parl( 7 ) ),
                            MAPI_DIALOG, 0 ), 0 ) );
   }
   else
   {
      MessageBox( GetActiveWindow(), "No MAIL session active",
                  "Attention", MB_ICONEXCLAMATION );
      _retnl( 0 );
   }
}

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