// PluginAdapterV1.cpp : Implementation of cPluginAdapterV1
#include "stdafx.h"
#include "Inject.h"
#include "PluginAdapterV1.h"

#include "Manager.h"

/////////////////////////////////////////////////////////////////////////////
// cPluginAdapterV1

STDMETHODIMP cPluginAdapterV1::Initialize(IPluginSite2 *pSite2)
{
   // First retreive the Inject service
   CComPtr< IDecal > pDecal;
   pSite2->get_Decal ( &pDecal );

   CComPtr< IInjectService > pInject;
   HRESULT hRes = pDecal->get_Object ( _bstr_t ( _T( "services\\DecalPlugins.InjectService" ) ),
      __uuidof ( IInjectService ), reinterpret_cast< LPVOID * > ( &pInject ) );

   if ( FAILED ( hRes ) )
      return hRes;

   // Try to initialize our plugin
   CComPtr< IPlugin > pPlugin;
   hRes = m_pUnkPlugin->QueryInterface ( &pPlugin );
   if ( FAILED ( hRes ) )
      return hRes;

   CComPtr< IPluginSite > pSite;
   pInject->get_Site ( &pSite );

   try
   {
      pPlugin->Initialize ( pSite, 0 );
   }
   catch ( ... )
   {
      return E_FAIL;
   }

   pInject->InitPlugin ( m_pUnkPlugin );

   // Store the site if everything is OK
   m_pSite2 = pSite2;
   return S_OK;
}

STDMETHODIMP cPluginAdapterV1::Terminate()
{
   CComPtr< IPlugin > pPlugin;

   if ( SUCCEEDED ( m_pUnkPlugin->QueryInterface ( &pPlugin ) ) )
      pPlugin->Terminate ();

   m_pUnkPlugin.Release ();
   m_pSite2.Release ();

   return S_OK;
}

STDMETHODIMP cPluginAdapterV1::CreateInstance(IDecalEnum *pEnum, REFIID riid, LPVOID *ppvItf)
{
   CLSID clsidV1;
   HRESULT hRes = pEnum->get_ComClass ( &clsidV1 );
   if ( FAILED( hRes ) )
      return hRes;

   hRes = ::CoCreateInstance ( clsidV1, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, reinterpret_cast< LPVOID * > ( &m_pUnkPlugin ) );
   if ( FAILED ( hRes ) )
      return hRes;

   return static_cast< IDecalSurrogate * > ( this )->QueryInterface ( riid, ppvItf );
}
