// ScriptSiteImpl.cpp
// Implementation of IActiveScriptSiteImpl

#include "stdafx.h"
#include "ScriptSiteImpl.h"

HRESULT IActiveScriptSiteImpl::createScriptEngine( LPCOLESTR strLanguage )
{
   CLSID clsidScript;
	//CComPtr< IActiveScript > pScript;
   HRESULT hRes = ::CLSIDFromProgID( strLanguage, &clsidScript );

   _ASSERTE( SUCCEEDED( hRes ) );

   hRes = ::CoCreateInstance( clsidScript, NULL, CLSCTX_INPROC_SERVER, IID_IActiveScript, reinterpret_cast< void ** >( &m_pScript ) );
   _ASSERTE( SUCCEEDED( hRes ) );
	
   // Configure the script engine
	//pScript->Clone(&m_pScript);
   m_pScript->SetScriptSite( this );

   return hRes;
}

void IActiveScriptSiteImpl::addNamedItem( BSTR szName, IUnknown *pObject, DWORD dwFlags )
{
	USES_CONVERSION;
   HRESULT hRes = m_pScript->AddNamedItem( szName, dwFlags );

   cObject o( szName, pObject );

   m_objects.push_back( o );
}

STDMETHODIMP IActiveScriptSiteImpl::GetItemInfo(LPCOLESTR pstrName, DWORD dwReturnMask, IUnknown **ppunkItem, ITypeInfo **ppTypeInfo)
{
   // First look for the item
   for( cObjectList::iterator i = m_objects.begin(); i != m_objects.end(); ++ i )
   {
      if( ::wcscmp( i->m_strName, pstrName ) == 0 )
      {
         if( dwReturnMask & SCRIPTINFO_IUNKNOWN )
         {
            *ppunkItem = i->m_pObject;
            ( *ppunkItem )->AddRef();
         }

         if( dwReturnMask & SCRIPTINFO_ITYPEINFO )
         {
            CComPtr< IProvideClassInfo > pPCI;
            HRESULT hRes = i->m_pObject->QueryInterface( &pPCI );
            if( SUCCEEDED( hRes ) )
            {
               HRESULT hRes = pPCI->GetClassInfo( ppTypeInfo );
               _ASSERTE( SUCCEEDED( hRes ) );
            }
            else
               *ppTypeInfo = NULL;
         }

         return S_OK;
      }
   }

   // The item was not found
   return TYPE_E_ELEMENTNOTFOUND;
}

STDMETHODIMP IActiveScriptSiteImpl::OnScriptError(IActiveScriptError *pase)
{
   USES_CONVERSION;

   EXCEPINFO ei;
   DWORD dwCookie;
   ULONG uLine;
   LONG nChar;
   CComBSTR strLine;

   pase->GetExceptionInfo( &ei );
   pase->GetSourcePosition( &dwCookie, &uLine, &nChar );
   pase->GetSourceLineText( &strLine );

   TCHAR szError[ 1024 ];
   ::_stprintf( szError, _T( "0x%08X (%i, %i): %s" ),
      ei.wCode, uLine, nChar, OLE2T( ei.bstrDescription ) );

   ::MessageBox( NULL, szError, OLE2T( ei.bstrSource ), MB_ICONERROR | MB_OK );

   _ASSERTE( FALSE );

   return S_OK;
}
