// MessageVector.cpp : Implementation of cMessageVector

#include "stdafx.h"
#include "Inject.h"
#include "MessageVector.h"

#include "Message.h"

/////////////////////////////////////////////////////////////////////////////
// cMessageVector

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

   USES_CONVERSION;

   TCHAR strIndex[ 12 ];
   ::_stprintf( strIndex, _T( "%i" ), nIndex );

   *pVal = T2BSTR( strIndex );

   return S_OK;
}

STDMETHODIMP cMessageVector::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 cMessageVector::get_Member(VARIANT vIndex, VARIANT *pVal)
{
   _ASSERTE( pVal != NULL );

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

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

   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 )
      {
         i->m_pSchema->getValue( m_pSource, i, pVal );
         return S_OK;
      }
   }

   _ASSERTE( FALSE );
	return E_INVALIDARG;
}
