/*
*********************************************************************
*
*	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: ICLASSF.CPP
*
*	Purpose: Class factory for IEliza local server
*
*********************************************************************
*/

#include <windows.h>
#include "iclassf.h"
#include "pipesv.h"
#include "celiza.h"


extern int LockCount, ObjectCount ;
extern HWND hClient, hMainWnd ;
extern HINSTANCE hInst ;

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


CClassFactory::~CClassFactory(void)
{

}



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 ResultFromScode(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 ResultFromScode (CLASS_E_NOAGGREGATION) ;
	}

/*
Create a new data object.  QUery interface as requested.  If found,
create a local window to display the conversation being held with this
object, and store it the member variable of the CEliza.
go happily on our way.
*/

	CEliza * pEliza = new CEliza ( ) ;

   	if (pEliza->QueryInterface (riid, ppvObj) == NOERROR)
	{
		MDICREATESTRUCT mcs ;
		TCHAR ClientName [24] ;

		wsprintf (ClientName, TEXT("Client # %d"), ObjectCount) ;
		mcs.szClass = TEXT("ChannelClass") ;
    	mcs.szTitle = ClientName ;
    	mcs.hOwner = hInst ;
    	mcs.x = CW_USEDEFAULT ;
    	mcs.y = CW_USEDEFAULT ;
    	mcs.cx = CW_USEDEFAULT ;
    	mcs.cy = CW_USEDEFAULT ;
    	mcs.style = 0 ;
    	mcs.lParam = 0;

		pEliza->m_hWnd = (HWND) SendMessage (hClient, WM_MDICREATE, 0, (LPARAM)&mcs) ;
		pEliza->m_hEdit = GetDlgItem (pEliza->m_hWnd, IDC_INCOMING) ;


		ObjectCount ++ ;
		pEliza->Release ( ) ;

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



STDMETHODIMP CClassFactory::LockServer(BOOL bLock)
{
	if (bLock == TRUE)
	{
		LockCount ++ ;
	}
	else
	{
		LockCount -- ;
		if (LockCount == 0 && ObjectCount == 0)
		{
			DestroyWindow (hMainWnd) ;
		}
	}
	return NOERROR ;
}
