#include "hud.h"
#include "cl_util.h"
#include "parsemsg.h"

#define BAR_OFFSET640 4
#define BAR_OFFSET320 2
#define RINGWIDTH640 4
#define RINGWIDTH320 3


DECLARE_MESSAGE(m_Charge, Charge);

int CHudCharge::Init(void)
{	HOOK_MESSAGE(Charge);
	gHUD.AddHudElem(this);
	Reset();

	m_iFlags |= HUD_ACTIVE;
	return 1;
}

void CHudCharge::Reset()
{	m_flFill = 0;
	m_fChargeRing=true;
}

int CHudCharge::VidInit( void )
{	m_HUD_chargebar = gHUD.GetSpriteIndex( "mainbar" );
	m_HUD_chargeline = gHUD.GetSpriteIndex( "chargeline");
	m_HUD_chargering = gHUD.GetSpriteIndex( "chargering");
	return 1;
}

int CHudCharge::Draw(float fltime)
{	if (m_flFill==0)
	{	return 1;
	}	
	int iWidth = gHUD.GetSpriteRect(m_HUD_chargebar).right - gHUD.GetSpriteRect(m_HUD_chargebar).left;
	int iHeigth = gHUD.GetSpriteRect(m_HUD_chargebar).bottom - gHUD.GetSpriteRect(m_HUD_chargebar).top;
	
	int r,g,b,x,y;
	UnpackRGB(r,g,b, RGB_WHITEISH);
	x = (ScreenWidth - iWidth) * 0.5;
	
	//make sure it doesn't overlap the hud
	if (x<iWidth)
	{	x  = iWidth * 1.25;
	}

	y = ScreenHeight - iHeigth;
	SPR_Set(gHUD.GetSprite(m_HUD_chargebar), r, g, b);
	SPR_Draw(0, x, y, &gHUD.GetSpriteRect(m_HUD_chargebar));

	
	if (ScreenWidth<640)
	{	iWidth -= BAR_OFFSET320 * 2;
		x += BAR_OFFSET320;
	}
	else
	{	iWidth -= BAR_OFFSET640 * 2;
		x += BAR_OFFSET640;
	}

	int iBarWidth = m_flFill * iWidth;
	for (int i = 0;i<iBarWidth;i++)
	{	SPR_Set(gHUD.GetSprite(m_HUD_chargeline), r, g, b);
		SPR_DrawHoles(0, x + i, y, &gHUD.GetSpriteRect(m_HUD_chargeline));
	}	
	
	if(m_fChargeRing)
	{
		if (ScreenWidth<640)
		{	x -= RINGWIDTH640;
		}
		else
		{	x -= RINGWIDTH320;
		}
		x += iWidth/3;
		SPR_Set(gHUD.GetSprite(m_HUD_chargering), r, g, b);
		SPR_DrawHoles(0, x, y, &gHUD.GetSpriteRect(m_HUD_chargering));
	}
	return 1;
}

int CHudCharge:: MsgFunc_Charge(const char *pszName,  int iSize, void *pbuf )
{	BEGIN_READ( pbuf, iSize );
	int n = READ_BYTE();
	if(n>101)
	{
		m_fChargeRing = false;
		n-=101;
	}
	else
	{
		m_fChargeRing = true;
	}
	m_flFill = (float)n/100;	
	return 1;
}