#include "psblobsystem.h"

extern void DrawBeamHead(const beam &head, vec3_t vecStart, vec3_t vecDir);

PSBlobSystem::PSBlobSystem(int id, int type, int dmg, int speed):FXSystem(id,type)
{
	m_iId = id;
	m_flStartTime = gEngfuncs.GetClientTime();
	std::list<ent_ent_trail>::iterator iter = gHUD.m_Trail.FindEntEntTrail(id);
	
	//get start pos
	cl_entity_t *pClient = gEngfuncs.GetEntityByIndex( iter->startent );
	if (pClient)
	{	if (iter->attachment)
		{	m_vecStart = pClient->attachment[iter->attachment-1];
		}
		else
		{	m_vecStart = pClient->curstate.origin;
		}		
	}
	else
	{	ConsolePrint("Can't find start entity\n");
	}

	m_vecStart = pClient->curstate.origin;
	if (m_vecStart == vec3_t(0,0,0))
	{	ConsolePrint("(0,0,0) start pos\n");
	}
	m_vecPos = m_vecStart;
	m_iSpeed = speed;

	pClient = gEngfuncs.GetEntityByIndex( id );
	if (!pClient)
	{	ConsolePrint("Can't find beam ent\n");
	}
	vec3_t vecEnd = pClient->curstate.origin;
	m_vecDir = vecEnd-m_vecStart;
	VectorNormalize(m_vecDir);

	m_head.ent = iter->head.ent;
	m_head.flarea = iter->head.flarea;
	m_head.flareb = iter->head.flareb;
	for(int i = 0;i<9;i++)
		m_head.flareframe[i] = 0;				//TODO: add animation
	m_head.width = iter->head.width;			//TODO: base on dmg
}

void PSBlobSystem::draw()
{
	DrawBeamHead(m_head, m_vecPos, m_vecDir);
}

void PSBlobSystem::think(float time)
{
	//get ent pos
	cl_entity_t *pClient = gEngfuncs.GetEntityByIndex( m_iId );
	if (!pClient)
	{	ConsolePrint("PSBlobSystem think: can't find beam ent\n");
	}
	vec3_t vecEnd = pClient->curstate.origin;
	vec3_t vecDir = vecEnd-m_vecStart;
	float flMaxDist = vecDir.Length();
	VectorNormalize(vecDir);
	m_vecDir = vecDir;
	float flTimeDiff = time - m_flStartTime;
	/*	
	char buffer[255];
	sprintf(buffer,"ID %d, Start pos: %f,%f,%f\n",m_iId,m_vecStart.x,m_vecStart.y,m_vecStart.z);	
	ConsolePrint(buffer);
	
	sprintf(buffer,"ID %d, End pos: %f,%f,%f\n",m_iId,vecEnd.x,vecEnd.y,vecEnd.z);	
	ConsolePrint(buffer);

	sprintf(buffer,"ID %d, Direction: %f,%f,%f\n",m_iId,vecDir.x,vecDir.y,vecDir.z);	
	ConsolePrint(buffer);

	sprintf(buffer,"ID %d, Time diff: %f\n",m_iId,flTimeDiff);	
	ConsolePrint(buffer);
	*/
	float flDist = flTimeDiff * (float)m_iSpeed;
	/*
	sprintf(buffer,"ID %d, Distance: %f\n",m_iId,flDist);
	ConsolePrint(buffer);

	sprintf(buffer,"ID %d, Max distance: %f\n",m_iId,flMaxDist);
	ConsolePrint(buffer);
	*/
	if(flDist>flMaxDist)
	{
		m_fRemove = true;
	}
	else
	{	m_vecPos = m_vecStart + vecDir * flDist;
	}
}