// ------------------------------------------------------------------------
/*
	author: Jaap Suter
   
	Copyright (C) Electronic Arts Canada Inc. 2002.  All rights reserved.	
*/
// ------------------------------------------------------------------------

/*! \file */


#include "reveal/context/context_container.h"

#include "reveal/input_state.h"
#include "reveal/renderer.h"

namespace Reveal {
	namespace Context {

// ------------------------------------------------------------------------------
/*!
	\brief Todo;
*/
// ------------------------------------------------------------------------------
void ContextContainer::Render( const Renderer& renderer ) const
{
	if ( mState == PICKED )
	{
		assert( mPickedObject );
		mPickedObject->RenderMenu( renderer );
	}
}

bool ContextContainer::Handle( const InputState& inputState, const Renderer& renderer )
{
	bool bResult = false;

	if ( mState == IDLE )
	{
		if (    inputState.Released( InputState::RIGHT_MOUSE )
			 || inputState.Pressed(  InputState::LEFT_MOUSE ) )
		{
			float x0( 0 ), y0( 0 ), z0( 0 );
			float xr( 0 ), yr( 0 ), zr( 0 );

			bool r = renderer.ScreenSpaceToWorldSpace( inputState.MouseX(), inputState.MouseY(), x0, y0, z0, xr, yr, zr );
			if ( r )
			{
				mPickedObject = 0;
				for ( size_t i = 0; i < MAX_NUM_OBJECTS; ++i )
				{						
					float distance = -1.0f;
	
					if ( mObjects[ i ].Get() )
					{
						float d = mObjects[ i ]->DistanceFromRay( x0, y0, z0, xr, yr, zr );
						if ( d > 0.0f )
						{
							if ( (distance == -1.0f) || (d < distance) )
							{
								distance = d;
								mPickedObject = mObjects[ i ].Get();
							}
						}
					}
				}
			}
			
			if ( mPickedObject )
			{
				if ( inputState.Released( InputState::RIGHT_MOUSE ) )
				{
					mPickedObject->EnableAndShowContext( inputState.MouseX(), inputState.MouseY() );
					mState = PICKED;
				}				
				else
				if ( inputState.Pressed( InputState::LEFT_MOUSE ) )
				{
					mState = CLICKED_AND_HOLD;
				}
				bResult = true;
			}
		}
	}
	else
	if ( mState == PICKED )
	{
		assert( mPickedObject );
		
		if ( !mPickedObject->HandleMenu( inputState ) || inputState.Pressed( InputState::RIGHT_MOUSE ) )
		{
			mPickedObject = 0;
			mState = IDLE;
		}

		bResult = true;
	}
	else
	if ( mState == CLICKED_AND_HOLD )
	{
		if ( ! inputState.Down( InputState::LEFT_MOUSE ) )
		{
			mPickedObject = 0;
			mState = IDLE;
		}
		else
		{
			mPickedObject->ClickAndHold( inputState );
		}

		bResult = true;
	}

	return bResult;
}

	}; // Namespace Context

} // Namespace Reveal;
