/*********************************************************************//**
*	Creatures
*	Abstraktni trida definuje entity, ktere lze povazovat za bytosti:
*		- hrac a monstra
*	
*	author: Michal Jirous
*	date: 23.04.2009
*	file: ent_creatures.cpp
**********************************************************************/

#include "ent_creatures.h"
#include "level_bspfile_def.h"

Creatures::Creatures() : CBasePhysics()
{
	m_iHealth = 100;
	m_iMaxHealth = 100;
	m_bIsDeath = false;
	m_iMaterial = MATERIAL_FLESH;
}



void Creatures::setHealth( int hlt )
{
	m_iHealth = getFromRange( hlt, 0, m_iMaxHealth );
	if( m_iHealth == 0 )
		die();
}

void Creatures::restart()
{
	CBasePhysics::restart();
	m_iHealth = m_iMaxHealth;
	m_bIsDeath = false;
}
#include "game.h"
void Creatures::onAttack( const AttackInfo &attackInfo )
{
	setHealth( m_iHealth - std::min( m_iHealth, attackInfo.m_iDamage ) );

	m_BackTimeData.push_front( BackTimeData() );
	m_BackTimeData.front().event_time = game.getGameTime();
	m_BackTimeData.front().type = EVENT_HEALTH;
	m_BackTimeData.front().values.event = m_iHealth;
}


 bool Creatures::collisionDetection( CollisionData &collData )
 {
	if( m_bIsDeath )
		return false;
	return CBasePhysics::collisionDetection( collData );
 
 }

bool Creatures::rayTrace(  RayTraceData &rayData )
{
	if( m_bIsDeath )
		return false;
	return CBasePhysics::rayTrace( rayData );
}


void Creatures::passStoredEvent( BackTimeData &backData )
{
	CBasePhysics::passStoredEvent( backData );

	if( backData.type == EVENT_DEATH && !m_bIsDeath)
	{
		die();
	}
	else if( backData.type == EVENT_HEALTH )
		m_iHealth = backData.values.event;
}

void Creatures::die()
{ 
	m_bIsDeath = true;

	m_BackTimeData.push_front( BackTimeData() );
	m_BackTimeData.front().event_time = game.getGameTime();
	m_BackTimeData.front().type = EVENT_DEATH;
}

void Creatures::goBackInTime()
{
	CBasePhysics::goBackInTime();

	int h = -1;
	bool deathFound = false;

	for( std::list<BackTimeData>::reverse_iterator riter = m_BackTimeData.rbegin(); riter != m_BackTimeData.rend(); ++riter )
	{
		if( (*riter).type == EVENT_BORDER )	//na border bych tu nemel narazit
			return;

		if( !deathFound )
		{
			if( (*riter).type == EVENT_DEATH )
			{
				m_bIsDeath = false;
				deathFound = true;
			}
			else if( (*riter).type == EVENT_RAISE_FROM_DEATH )
			{
				m_bIsDeath = true;
				deathFound = true;
			}
		}
		else if( h == -1 && (*riter).type == EVENT_HEALTH )
			h = (*riter).values.event;
		
	}
	if( h >= 0 )
		m_iHealth = h;
}
