/*
*********************************************************************
*
*	The Essence of OLE
*
*	Source code sample
*
*	Copyright (c) 1996, Rolling Thunder Computing, Ipswich MA
*
*	e-mail: essence@rollthunder.com
*	CompuServe: 73540,3430
*	Web: http://www.rollthunder.com
*
*	File Name: CCLASSF.CPP
*
*	Purpose: IClassFactory implementation for persistent data object sample
*
*********************************************************************
*/

#include <windows.h>
#include "cclassf.h"
#include "cpertimedata.h"


extern HWND hMainWnd ;
extern int LockCount, ObjectCount ;
extern CPersistTimeData *lpFirstObj ;

CClassFactory::CClassFactory (void)
{
    m_RefCount = 1 ;
	AddRef( ) ;   
    return;
}


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



STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, LPVOID *ppv)
{
    if (IsEqualIID(riid, IID_IUnknown)
        || IsEqualIID(riid, IID_IClassFactory))
	{
        *ppv = (LPVOID)this;
		AddRef( ) ;
		return NOERROR;
	}
	else
	{
    	*ppv = NULL ;
    	return  E_NOINTERFACE ;
	}
        
}


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


STDMETHODIMP_(ULONG) CClassFactory::Release(void)
{
	m_RefCount -- ;

    if (m_RefCount == 0)
	{
        delete this;
		return 0 ;
	}

    return m_RefCount ;
}



					  	
STDMETHODIMP CClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, 
	REFIID riid, LPVOID* ppvObj)
{
	    
/*
Check for aggregation request.  We don't do it.
*/
	if (pUnkOuter != NULL)
	{
		*ppvObj = NULL ;
		return  CLASS_E_NOAGGREGATION ;
	}

/*
Create a new data object.  QUery interface as requested.  If found,
go happily on our way.
*/

	CPersistTimeData * pTD = new CPersistTimeData ( ) ;

   	if (pTD->QueryInterface (riid, ppvObj) == NOERROR)
	{
		pTD->Release ( ) ;
		ObjectCount ++ ;

		if (!lpFirstObj)
		{
			lpFirstObj = pTD ;
		}

		return NOERROR ;
	}
	else
	{
		delete pTD ;
		return E_NOINTERFACE ;
	}
}


STDMETHODIMP CClassFactory::LockServer(BOOL bLock)
{
	MessageBox (NULL, "LockServer", "", 0) ;

	if (bLock == TRUE)
	{
		LockCount ++ ;
	}
	else
	{
		LockCount -- ;

		if (LockCount == 0 && ObjectCount == 0)
		{
			PostMessage (hMainWnd, WM_CLOSE, 0, 0) ;
		}
		else
		{
			InvalidateRect (hMainWnd, NULL, TRUE) ;
		}
	}
	return NOERROR ;
}
