//
// AVP_ClientEntity_InteractionTrigger.cpp
//
// Created by Chris Wallace - 06-March-2007
// 
// Copyright (C) 2007 Rebellion, All Rights Reserved.
//

#include "Core/Asura.h"

#include "Entity/Triggers/AVP_ClientEntity_InteractionTrigger.h"

#include "Entity/Asura_Entity_Classification.h"
#include "Network/Asura_Message.h"

#include "Entity/AVP_Messages.h"
#include "Entity/PhysicalObject/Actor/AVP_Actor_Messages.h"

Asura_Hashed_List<AVP_ClientEntity_InteractionTrigger> AVP_ClientEntity_InteractionTrigger::s_xList;

AVP_ClientEntity_InteractionTrigger::AVP_ClientEntity_InteractionTrigger( Asura_Guid uGuid )
: Asura_ClientEntity_AdvancedVolumeTrigger(uGuid)
{
	Classification = AVP_ENTITYCLASS_INTERACTIONTRIGGER;

	SetActive(true);
	
	s_xList.AddToList( this );
}

AVP_ClientEntity_InteractionTrigger::~AVP_ClientEntity_InteractionTrigger()
{
	s_xList.RemoveFromList(this);
}

bool AVP_ClientEntity_InteractionTrigger::IsTriggered(void)
{
	return false;
}

bool AVP_ClientEntity_InteractionTrigger::IsUnTriggered(void)
{
	return false;
}


bool AVP_ClientEntity_InteractionTrigger::Contains(const Asura_Vector_3& xPosition) const
{
	for(int i=0;i<m_iNumberOfVolumes;i++)
	{
		if(m_pxVolumes[i].Contains(xPosition))
		{
			return true;
		}
	}
	return false;
}

void AVP_ClientEntity_InteractionTrigger::OnUnTrigger()
{
	Asura_ClientEntity_Trigger::OnUnTrigger();
	if(m_bTriggerOnce && m_bActive)
	{
		//deactivate this trigger so it doesn't get triggered again
		OnDeactivation();
		m_bActive = false;
	}
}

bool AVP_ClientEntity_InteractionTrigger::HandleMessage(const Asura_Message* pxMessage)
{
	if (pxMessage)
	{
		switch (pxMessage->GetMsgID())
		{
		case ASURA_MSG_CLIENTUPDATE:
			{
				const AVP_Message_InteractionTrigger_ClientUpdate* pxMsgData = static_cast<const AVP_Message_InteractionTrigger_ClientUpdate*>( pxMessage->GetData() );
				ProcessClientUpdate(pxMsgData);
				return(true);
			}

		case AVP_MSGID_REQUEST_INTERACTION:
			{
				const AVP_Message_Actor_RequestInteraction* pxData = static_cast<const AVP_Message_Actor_RequestInteraction*>(pxMessage->GetData());
				if (pxData->GetInteractionType() == AVP_INTERACTION_TYPE_DEFAULT)
				{
					// trigger ourselves.
					if (IsActive())
					{
						OnTrigger();
					}
				}
				// TODO - should we return false if a different interaction type was sent?
				return true;
			}

		default:
			{
				return(PARENT::HandleMessage(pxMessage));
			}
			
		}
	}

	return(false);
}

void AVP_ClientEntity_InteractionTrigger::ProcessClientUpdate(const AVP_Message_InteractionTrigger_ClientUpdate* pxData)
{
	m_iListFlags		= pxData->GetListFlags();
	m_iNumberOfVolumes	= pxData->GetNumVolumes();
	m_pxVolumes[0]		= *pxData->GetVolume();
}

void AVP_ClientEntity_InteractionTrigger::Create(const Asura_Message* pxMessage)
{
	AVP_ClientEntity_InteractionTrigger*	pxClient	= new AVP_ClientEntity_InteractionTrigger(pxMessage->GetFromGuid());

	// Initialise the entity...
	pxClient->HandleMessage(pxMessage);
}
