// MessageStruct.cpp : Implementation of cMessageStruct
#include "stdafx.h"
#include "Inject.h"
#include "MessageStruct.h"

#include "Message.h"

/////////////////////////////////////////////////////////////////////////////
// cMessageStruct


STDMETHODIMP cMessageStruct::get_Count(long *pVal)
{
   _ASSERTE( pVal != NULL );

   cMessage::cFieldList::iterator i_begin = m_pSource->m_fields.begin() + m_dwStartIndex;
   cMessage::cFieldList::iterator i_end = i_begin + i_begin->m_nOwns;

   *pVal = 0;

   for( cMessage::cFieldList::iterator i = i_begin + 1; i != i_end; i += i->m_nOwns )
      ++ ( *pVal );

	return S_OK;
}

STDMETHODIMP cMessageStruct::get_MemberName(long Index, BSTR *pVal)
{
   _ASSERTE( pVal != NULL );
   _ASSERTE( Index >= 0 );

   USES_CONVERSION;

   cMessage::cFieldList::iterator i_begin = m_pSource->m_fields.begin() + m_dwStartIndex;
   cMessage::cFieldList::iterator i_end = i_begin + i_begin->m_nOwns;

   for( cMessage::cFieldList::iterator i = i_begin + 1; i != i_end; i += i->m_nOwns, -- Index )
   {
      if( Index == 0 )
      {
         *pVal = OLE2BSTR( i->m_pSchema->m_strName );
         return S_OK;
      }
   }

   _ASSERTE( FALSE );
	return E_INVALIDARG;
}

STDMETHODIMP cMessageStruct::get_Member(VARIANT vIndex, VARIANT *pVal)
{
   cMessage::cFieldList::iterator i_begin = m_pSource->m_fields.begin() + m_dwStartIndex;
   cMessage::cFieldList::iterator i_end = i_begin + i_begin->m_nOwns;

   if( vIndex.vt == VT_BSTR )
   {
      _bstr_t bstrIndex = vIndex;
      for( cMessage::cFieldList::iterator i = i_begin + 1; i != i_end; i += i->m_nOwns )
      {
         if( bstrIndex == i->m_pSchema->m_strName )
         {
            i->m_pSchema->getValue( m_pSource, i, pVal );
            return S_OK;
         }
      }
   }

   HRESULT hRes = ::VariantChangeType( &vIndex, &vIndex, 0, VT_I4 );
   if( FAILED( hRes ) )
   {
      _ASSERTE( FALSE );
      return hRes;
   }

   // Check if the value is in range
   long nIndex = vIndex.lVal;
   if( nIndex < 0 )
   {
      _ASSERTE( nIndex >= 0 );
      return E_INVALIDARG;
   }

   for( cMessage::cFieldList::iterator i = i_begin + 1; i != i_end; i += i->m_nOwns, -- nIndex )
   {
      if( nIndex == 0 )
      {
         i->m_pSchema->getValue( m_pSource, i, pVal );
         return S_OK;
      }
   }

	return S_OK;
}
