// RsDoFactory.cpp : Implementation of CRsDoFactory

#include "stdafx.h"
#include "RpExamplesPlugin.h"
#include "RsDoFactory.h"
#include "ExampleDataObject.h"

// CRsDoFactory

STDMETHODIMP CRsDoFactory::CreateInstance(const IID *riid, IRsDataObject** ppDataObj)
{
	BEGIN_DATAOBJECT_MAP()
		DATAOBJECT_ENTRY(riid, ppDataObj, IRdExampleDataObject, CRdExampleDataObject)
	END_DATAOBJECT_MAP()
    return E_INVALIDARG;
}

STDMETHODIMP CRsDoFactory::CreateAggInstance(IUnknown* pUnkOuter, const IID *riid, IUnknown** ppvObject)
{
	return E_NOTIMPL;
}


STDMETHODIMP CRsDoFactory::EnumDataObjDesc(IRsEnumDataObjDesc** ppEnumDataObjDesc)
{

    BEGIN_DATAOBJ_DESC_MAP()
        DATAOBJ_ENTRY(IRdExampleDataObject, CRpExamplesPlugin, /* fill object descriptor*/ 0, 0)		
	END_DATAOBJ_DESC_MAP()

	typedef CComEnum<IRsEnumDataObjDesc, &__uuidof(IRsEnumDataObjDesc), IRsDataObjDesc*, _CopyInterface<IRsDataObjDesc> > CRsEnumDataObjDesc;

	CComPtr<IRpKernel>	spKernelPackage;
	CRpExamplesPlugin::GetKernelPackage(&spKernelPackage);
	CComPtr<IRsSysFactory>	spFactory;
	spKernelPackage->GetSysFactory(&spFactory);

	CComObject<CRsEnumDataObjDesc>* pEnum;
	HRESULT hr = CComObject<CRsEnumDataObjDesc>::CreateInstance(&pEnum);
	if (FAILED(hr))	
		return hr;

	// number of the items in the descriptor array
	RtUlong lastIndex = sizeof(_dataObjDesc) / sizeof(_dataObjDesc[0]);

	// initialize array
	CInterfaceArray<IRsDataObjDesc>	arrayDesc;
	// fill array
	for (RtUlong i = 0; i< lastIndex; i++)
	{
		// create descriptor instance
		CComPtr<IRsDataObjDesc>	spDataObjDesc;
		spFactory->CreateDataObjDesc(&spDataObjDesc);
		
		// initialize descriptor
		spDataObjDesc->Initialize(&_dataObjDesc[i]);

		// add it to array
		arrayDesc.Add(spDataObjDesc);
	}
	
	// initialize enumerator so that caller takes ownership of the array
	hr = pEnum->Init((IRsDataObjDesc**)&arrayDesc[0].p, 
					 (IRsDataObjDesc**)&arrayDesc[lastIndex-1].p, NULL ,AtlFlagCopy );

	if (SUCCEEDED(hr))
		hr = pEnum->QueryInterface(ppEnumDataObjDesc);

    return hr;
}
