// PageLayout.cpp : Implementation of cPageLayout
#include "stdafx.h"
#include "DecalControls.h"
#include "PageLayout.h"

/////////////////////////////////////////////////////////////////////////////
// cPageLayout

void cPageLayout::onChildDestroy( long nID )
{
   if( m_nActive != -1 )
   {
      if( nID == m_pages[ m_nActive ] )
         // The active page is being deleted, now we show no pages
         m_nActive = -1;
   }

   // Walk through the list of pages and remove he who does
   // not exist
   for( cChildIDList::iterator i = m_pages.begin(); i != m_pages.end(); ++ i )
   {
      if( *i == nID )
      {
         m_pages.erase( i );
         break;
      }
   }
}

void cPageLayout::onSchemaLoad( IView *pView, MSXML::IXMLDOMElementPtr &pElement )
{
   // Each control child is a page
   MSXML::IXMLDOMElementPtr pChild;
   for( MSXML::IXMLDOMNodeListPtr pChildren = pElement->selectNodes( _T( "control" ) );
         ( pChild = pChildren->nextNode() ).GetInterfacePtr() != NULL; )
      m_pages.push_back( loadChildControl( pView, pChild ) );
}

STDMETHODIMP cPageLayout::get_Active(long *pVal)
{
   _ASSERTE( pVal != NULL );

   *pVal = m_nActive;

	return S_OK;
}

STDMETHODIMP cPageLayout::put_Active(long newVal)
{
   _ASSERTE( newVal >= 0 );
   _ASSERTE( newVal < m_pages.size() );

   if( m_nActive != -1 )
   {
      // Hide the active page
      CComPtr< ILayerSite > pChildSite;
      HRESULT hRes = m_pSite->get_Child( m_pages[ m_nActive ], ePositionByID, &pChildSite );
      _ASSERTE( SUCCEEDED( hRes ) );

      static RECT rcHide = { 0, 0, 0, 0 };
      pChildSite->put_Position( &rcHide );
   }

   m_nActive = newVal;

   // The reformat next cycle will reposition the child
   m_pSite->Reformat();

	return S_OK;
}

STDMETHODIMP cPageLayout::CreatePage(ILayer *pChild)
{
   _ASSERTE( pChild != NULL );

   LayerParams lp = { dispenseID(), { 0, 0, 0, 0 }, eRenderClipped };
   m_pSite->CreateChild( &lp, pChild );

   m_pages.push_back( lp.ID );

	return S_OK;
}

STDMETHODIMP cPageLayout::get_Count(long *pVal)
{
   _ASSERTE( pVal != NULL );
   *pVal = m_pages.size();

	return S_OK;
}

STDMETHODIMP cPageLayout::Reformat()
{
   if( m_nActive == -1 )
      return S_OK;

   // Get the active page and set it to fill our entire client area
   RECT rcThis;
   m_pSite->get_Position( &rcThis );

   RECT rcClient = { 0, 0, rcThis.right - rcThis.left, rcThis.bottom - rcThis.top };

   CComPtr< ILayerSite > pChild;
   HRESULT hRes = m_pSite->get_Child( m_pages[ m_nActive ], ePositionByID, &pChild );
   _ASSERTE( SUCCEEDED( hRes ) );

   pChild->put_Position( &rcClient );

   return S_OK;
}
