#include "Entity.h"
#include "GameLogic.h"
#include "Swatter.h"

int Entity::m_nextID = 1; //start 'em off here

Entity::Entity()
{
  m_sprite = NULL;

  SetType(C_TYPE_UNKNOWN);
  m_ID = m_nextID++;
  SetDeleteFlag(false);
  m_bPosTargetActive = false;
  m_vScale = CL_Vector2(1,1);
  m_vVelocity = CL_Vector2(0,0);
  m_vPosition = CL_Vector2(0,0);
  m_vHeading = CL_Vector2(0, -1);
  m_sort = 1000;
  m_radius = 10;
  m_bScaleToNothing = false;
  m_bScaleUp = false;
  m_bFadeAlphaTo = false;
  m_alphaTarget = 0;
  m_alpha = 1;
  m_alphaFadeSpeed = 0.05f;

}

Entity::~Entity()
{
   
	SAFE_DELETE(m_sprite);

	if (GetGameLogic && GetGameLogic->ShuttingDown() == false)
	{
		GetGameLogic->GetMessageDispatcher()->KillAllMessagesToThisEnt(this);
	}
}

void Entity::SetPosTarget(const CL_Vector2 &v)
{
	m_bPosTargetActive = true; 
	m_vPosTarget = v;
}

void Entity::Update(float step)
{

if (m_bPosTargetActive)
{
	m_vPosition.x = LerpFloat(m_vPosition.x, m_vPosTarget.x, 0.1f * step);
	m_vPosition.y = LerpFloat(m_vPosition.y, m_vPosTarget.y, 0.1f * step);
}
	

  if (m_bScaleToNothing)
    {
        m_vScale.x = LerpFloat(m_vScale.x, 0, 0.05f * step);
        m_vScale.y = LerpFloat(m_vScale.y, 0, 0.05f* step);
    }


    if (m_bScaleUp)
    {
        m_vScale.x = LerpFloat(m_vScale.x, 3, 0.05f * step);
        m_vScale.y = LerpFloat(m_vScale.y, 3, 0.05f * step);

    }
  
    if (m_bFadeAlphaTo)
    {
       m_alpha = LerpFloat(m_alpha, m_alphaTarget, m_alphaFadeSpeed * step);
    }
	if (m_sprite) 
	{

		m_sprite->update();
		m_sprite->set_alpha(m_alpha);

	}

}

void Entity::OnMessage(Message &msg)
{
    switch(msg.m_msg)
    {
    case C_MESSAGE_KILL_ENTITY:

        SetDeleteFlag(true);
        break;

	case C_MESSAGE_FADE_OUT_AND_DIE:

		m_bFadeAlphaTo = true;
		m_alphaTarget = 0;
		GetGameLogic->GetMessageDispatcher()->SendMsg(C_MESSAGE_KILL_ENTITY, 1000, this);
		break;
    }
}

void Entity::Render()
{
	if (m_sprite)
	{

	
	m_sprite->set_scale(m_vScale.x, m_vScale.y);
	m_sprite->set_alpha(m_alpha);
	m_sprite->draw(m_vPosition.x, m_vPosition.y);
	}

}

bool Entity::TouchingPlayer()
{
	assert(g_pSwatter);

	CL_Rect pr(g_pSwatter->m_vPosition.x, g_pSwatter->m_vPosition.y, 
		g_pSwatter->m_vPosition.x + g_pSwatter->m_sprite->get_width(),
		g_pSwatter->m_vPosition.y + g_pSwatter->m_sprite->get_height());

	CL_Rect r(m_vPosition.x, m_vPosition.y, 
		m_vPosition.x + m_sprite->get_width(), m_vPosition.y + m_sprite->get_height());
	
	if (pr.is_overlapped(r))
	{
		return true;
	} else
		return false;
}
 