// ScriptView.cpp : Implementation of CScriptView
#include "stdafx.h"
#include "PlainText.h"
#include "ScriptView.h"

/////////////////////////////////////////////////////////////////////////////
// CScriptView


void CScriptView::loadView( cScriptPlugin *pPlugin, MSXML::IXMLDOMElementPtr &pView, LPDISPATCH *ppNewView )
{
   USES_CONVERSION;

	// Get IPluginSite
   CComPtr< IDecal > pDecal;
	CComPtr< IInjectService > pInject;
   pPlugin->m_pSite->get_Decal ( &pDecal );
   pDecal->get_Object ( _bstr_t ( _T( "services\\DecalPlugins.InjectService" ) ),
      __uuidof ( IInjectService ), reinterpret_cast< LPVOID * > ( &pInject ) );

   pInject->get_Site(&m_pOldSite);

   m_pPlugin = pPlugin;

   // Initialize a new script engine
   CComBSTR strLanguage;
   pPlugin->getLanguage( &strLanguage );

   HRESULT hRes = createScriptEngine( strLanguage );

   CComPtr< IActiveScriptParse > pParse;
   m_pScript->QueryInterface( &pParse );

   pParse->InitNew();

   m_pOldSite->LoadViewObject( pView, &m_pView );

   IViewEventsImpl< VIEW_ID, CScriptView >::DispEventAdvise( m_pView );

   // Add in the plugin
   CComPtr< IDispatch > pDispPlugin;
   pPlugin->m_pScript->GetScriptDispatch( NULL, &pDispPlugin );
   addNamedItem( T2OLE( _T( "Plugin" ) ), pDispPlugin );

   // Add in the site
   addNamedItem( T2OLE( _T( "Site" ) ), static_cast< IDispatch * >( pPlugin ) );

   // Add in the view as a base object
   addNamedItem( T2OLE( _T( "View" ) ), static_cast< IDispatch * >( m_pView ) );

   MSXML::IXMLDOMElementPtr pScript = pView->selectSingleNode( _T( "script" ) );

   if( pScript.GetInterfacePtr() != NULL )
   {
      EXCEPINFO ei;
      HRESULT hRes = pParse->ParseScriptText( pScript->text, NULL, NULL, NULL, 0, 0, 
         SCRIPTTEXT_ISVISIBLE, NULL, &ei );

      _ASSERTE( SUCCEEDED( hRes ) );
   }

   MSXML::IXMLDOMNodeListPtr pControls = pView->selectNodes( _T( ".//control[@name]" ) );
   for( MSXML::IXMLDOMElementPtr pControl = pControls->nextNode(); pControl.GetInterfacePtr() != NULL; pControl = pControls->nextNode() )
   {
      CComPtr< IControl > pCtl;
      _bstr_t strName = pControl->getAttribute( _T( "name" ) ).bstrVal;
      m_pView->get_Control( strName, &pCtl );
      addNamedItem( strName, pCtl );
   }

   // Add ourself into the view list
   m_pPlugin->m_views.push_back( this );

   m_pScript->SetScriptState( SCRIPTSTATE_CONNECTED );
   m_pScript->GetScriptDispatch( NULL, ppNewView );

   _ASSERTE( *ppNewView != NULL );

   Fire_Initialize();
}

void CScriptView::destroy()
{
   Fire_Terminate();
   IViewEventsImpl< VIEW_ID, CScriptView >::DispEventUnadvise( m_pView );

   m_pScript->SetScriptState( SCRIPTSTATE_DISCONNECTED );
   m_pScript->Close();

   // Remove ourself from the list, the next line might destroy this object
   m_pView.Release();
   m_pPlugin->removeView( this );
}
