#include <windows.h>
#include "cadvsink.h"

extern HWND hMainWnd ;
extern SYSTEMTIME st ;
extern UINT cfTimeData, cfThreadId ;

CAdviseSink::CAdviseSink()
{
	m_RefCount = 1 ;
    return;
}

CAdviseSink::~CAdviseSink(void)
{
    return;
}


STDMETHODIMP CAdviseSink::QueryInterface(REFIID riid, LPVOID *ppv)
{
    if (IsEqualIID(riid, IID_IUnknown)
        || IsEqualIID(riid, IID_IAdviseSink))
    {
	    *ppv = (LPVOID)this;  
        AddRef();
        return S_OK ;
    }
    else
    {
    	*ppv = NULL;       
    	return  ResultFromScode(E_NOINTERFACE) ;
    }
}


STDMETHODIMP_(ULONG) CAdviseSink::AddRef(void)
{
    m_RefCount ++ ;
    return m_RefCount ;
}

STDMETHODIMP_(ULONG) CAdviseSink::Release(void)
{
    ULONG ReleaseCount ;

    m_RefCount -- ;
    ReleaseCount = m_RefCount ;
    
    if (m_RefCount == 0L)
    {   
    	delete this;
    }

    return ReleaseCount ;
}




STDMETHODIMP_(void) CAdviseSink::OnViewChange(DWORD dwAspect, LONG lindex)
{
    return;
}



STDMETHODIMP_(void) CAdviseSink::OnDataChange(LPFORMATETC pFEIn, LPSTGMEDIUM pSTM)
{


/*
Get ID of the thread from which this call originated. This is
in the data sent by the object.
*/
	DWORD *pdw ;
	UINT CallerThreadId ;

	if (pFEIn->cfFormat == cfThreadId)
	{
		pdw = (DWORD *)GlobalLock (pSTM->hGlobal) ;
		CallerThreadId = *pdw ;
		GlobalUnlock (pSTM->hGlobal) ;
	}

/*
Get the current thread ID, which is the ID of the thread on which
this call is received.
*/

	DWORD CurrentThreadID  = GetCurrentThreadId( ) ;

/*
Draw both on the screen for the user to see.
*/

	MessageBeep (0) ; 

	HDC hDC = GetDC (m_hWnd) ;
	char out [128] ; int length ;

	length = wsprintf (out, "Callback originated on thread ID == 0x%x", CallerThreadId) ;
	TextOut (hDC, 0, 50, out, length) ;

	length = wsprintf (out, "Callback received on thread ID == 0x%x", CurrentThreadID) ;
	TextOut (hDC, 0, 70, out, length) ;

	ReleaseDC (m_hWnd, hDC) ;
    return;
}


STDMETHODIMP_(void) CAdviseSink::OnRename(LPMONIKER pmk)
{
    return;
}

STDMETHODIMP_(void) CAdviseSink::OnSave(void)
{
	return;
}

STDMETHODIMP_(void) CAdviseSink::OnClose(void)
{
    return;
}
