#include <windows.h>
#include "cclassf.h"
#include "ctimedta.h"
#include "main.h"

extern HWND hMainWnd ;
extern CTimeData *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 ;
}



extern CRITICAL_SECTION csShutdown ;
extern BOOL bShuttingDownNow ;

STDMETHODIMP CClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, 
	REFIID riid, LPVOID* ppvObj)
{
	HRESULT retval ;

/*
Wait on critical section to make sure no one is in a race condition.
*/

	EnterCriticalSection (&csShutdown) ;

	if (bShuttingDownNow)
	{
		retval = CO_E_SERVER_STOPPING ;
	}

/*
Check for aggregation request.  We don't do it.
*/
	else if (pUnkOuter != NULL)
	{
		*ppvObj = NULL ;
		retval = CLASS_E_NOAGGREGATION ;
	}

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

		CTimeData * pTD = new CTimeData ( ) ;

		retval = pTD->QueryInterface (riid, ppvObj) ;

		if (retval == S_OK)
		{
			pTD->Release ( ) ;

			if (!lpFirstObj)
			{
				lpFirstObj = pTD ;
			}
		}
		else
		{
			delete pTD ;
		}
	}

	LeaveCriticalSection (&csShutdown) ;
	return retval ;
}

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

	if (bLock == TRUE)
	{
		LockThisObjectsServer ( ) ;
	}
	else
	{
		UnlockThisObjectsServer ( ) ;
	}

	return S_OK ;
}
