// ChoicePopup.cpp : Implementation of cChoicePopup
#include "stdafx.h"
#include "DecalControls.h"
#include "ChoicePopup.h"

#include "Choice.h"

/////////////////////////////////////////////////////////////////////////////
// cChoicePopup

#define ROW_HEIGHT 18

void cChoicePopup::hotSelect( MouseState *pMS )
{
   if( pMS->over != this )
      m_pChoice->m_nHotSelect = -1;
   else
   {
      m_pChoice->m_nHotSelect = pMS->client.y / ROW_HEIGHT;

      if( m_pChoice->m_nHotSelect >= m_pChoice->m_options.size() )
         // If we went over the edge, kill the selection
         m_pChoice->m_nHotSelect = -1;
   }

   m_pSite->Invalidate();
}

void cChoicePopup::onCreate()
{
   CComPtr< IPluginSite > pPlugin;
   m_pSite->get_PluginSite( &pPlugin );

   pPlugin->LoadBitmapPortal( 0x0600127A, &m_pActive );

   m_pSite->put_Transparent( VARIANT_FALSE );
}

void cChoicePopup::onDestroy()
{
   m_pActive.Release();
}

#define RENDER_LEFTSTRETCH 10
#define RENDER_RIGHTSTRETCH 7

STDMETHODIMP cChoicePopup::Render(ICanvas *pCanvas)
{
   int nHighlight = ( m_pChoice->m_nHotSelect == -1 ) ? m_pChoice->m_nSelected : m_pChoice->m_nHotSelect;

   RECT rc;
   m_pSite->get_Position( &rc );

   long nWidth = rc.right - rc.left;

   SIZE szImage;
   m_pActive->get_Size( &szImage );

   long nRightStretch = szImage.cx - RENDER_RIGHTSTRETCH;

   for( cChoice::cOptionList::iterator i = m_pChoice->m_options.begin(); i != m_pChoice->m_options.end(); ++ i )
   {
      int nRow = i - m_pChoice->m_options.begin();
      bool bHighlight = ( nRow == nHighlight );
      POINT ptDest = { 0, nRow * ROW_HEIGHT };

      // Draw the background image
      ( ( bHighlight ) ? m_pActive : m_pChoice->m_pInactive )->StretchBlt( pCanvas, &ptDest, nWidth, RENDER_LEFTSTRETCH, nRightStretch );

      // Draw the text
      POINT ptText = { 12, nRow * ROW_HEIGHT + 2 };
      m_pChoice->m_pFont->DrawTextEx( &ptText, i->m_strText, 0, 0, eAA, pCanvas );
   }

   return S_OK;
}

STDMETHODIMP cChoicePopup::MouseUp(MouseState *pMS)
{
   // Set the selection
   m_bMouseDown = false;
   hotSelect( pMS );

   if( m_pChoice->m_nHotSelect != -1 )
      m_pChoice->put_Selected( m_pChoice->m_nHotSelect );

   m_pChoice->m_pSite->Invalidate();

   // Hide the popup
   m_pChoice->setPopup( false );
   m_pChoice->m_pPopup->put_Popup( VARIANT_FALSE );

   // Clear the selection
   m_pSite->Invalidate();

   return S_OK;
}
