#include <windows.h>
#include <initguid.h>
#include "ieliza.h"
#include "cmarshal.h"


CMarshal::CMarshal (LPUNKNOWN pUnkOuter)
{
	m_pUnkOuter = pUnkOuter ;
    return;
}


CMarshal::~CMarshal(void)
{

/*
Object being destroyed, signal final release to the server
*/

	*(DWORD *) m_pSharedMem = 1 ;
	SetEvent (m_hComplaintEvent) ;


    return;
}



STDMETHODIMP CMarshal::QueryInterface(REFIID riid, LPVOID *ppv)
{
	return m_pUnkOuter->QueryInterface (riid, ppv) ;
}


STDMETHODIMP_(ULONG) CMarshal::AddRef(void)
{
	return m_pUnkOuter->AddRef ( ) ;
}


STDMETHODIMP_(ULONG) CMarshal::Release(void)
{
	return m_pUnkOuter->Release ( ) ;
}

STDMETHODIMP CMarshal::GetUnmarshalClass (REFIID riid, VOID* pVoid, DWORD dwDestCtx, VOID*, DWORD, 
	CLSID *pClsid )
{
	MessageBox (NULL, "Unexpected GetUnmarshalClass", "Proxy", 0) ;
	return S_OK ;

}

STDMETHODIMP CMarshal::GetMarshalSizeMax (REFIID riid, VOID* pv, DWORD dwDestCtx, 
	VOID* pvReserved, DWORD dwFlags, DWORD *pSize)
{
	MessageBox (NULL, "Unexpected GetMarshalSizeMax", "Proxy", 0) ;
	return S_OK ;
}

STDMETHODIMP CMarshal::MarshalInterface (IStream *pStream, REFIID riid, 
	VOID * pv, DWORD dwDestCtx, VOID *pvReserved, DWORD dwFlags)
{

	MessageBox (NULL, "Unexpected MarshalInterface", "Proxy", 0) ;
	return S_OK ;
}

STDMETHODIMP CMarshal::UnmarshalInterface (IStream *pStream, REFIID riid, VOID **ppv)
{

/*
Read file mapping name from pStream.  Create file mapping
and map memory pointer for that name.  Also open the events that the server
should have already created.
*/

	pStream->Read (m_ShareName, sizeof(m_ShareName), NULL) ;

	char out [256] ;
	wsprintf (out, "%sMap", m_ShareName) ;
	
	m_hMap = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, out) ;

	if (!m_hMap)
	{
		MessageBox (NULL, "Couldn't Open Map", "Proxy", 0) ;
	}

	m_pSharedMem = (LPTSTR) MapViewOfFile (m_hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0) ;
	
	wsprintf (out, "%sComplaintEvent", m_ShareName) ;
	m_hComplaintEvent = OpenEvent (EVENT_MODIFY_STATE, FALSE, out) ;
	if (!m_hComplaintEvent)
	{
		MessageBox (NULL, "Couldn't Open Complaint Event", "Proxy", 0) ;
	}

	
	wsprintf (out, "%sResponseEvent", m_ShareName) ;
	m_hResponseEvent = OpenEvent (EVENT_ALL_ACCESS, FALSE, out) ;
	if (!m_hResponseEvent)
	{
		MessageBox (NULL, "Couldn't Open Response Event", "Proxy", 0) ;
	}

/*
return pointer to IEliza interface
*/

	*ppv = m_pUnkOuter ;
	AddRef ( ) ;
	return S_OK ;
}

STDMETHODIMP CMarshal::ReleaseMarshalData (IStream *pStream)
{
//	MessageBox (NULL, "ReleaseMarshalData", "Proxy", 0) ;
	return S_OK ;
}

STDMETHODIMP CMarshal::DisconnectObject (DWORD dwReserved)
{
	return S_OK ;
}
