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

Swatter *g_pSwatter = NULL;
#define C_SWAT_FINISH_PADDING 80

Swatter::Swatter()
{
	m_movementMode = C_MOVE_ANYWHERE;
	m_rectLimit = 	CL_Rect(0,0, GetScreenX, GetScreenY);
	//wire up the mouse to us

	m_slots.connect(CL_Mouse::sig_key_down(), this, &Swatter::OnButtonDown);
	m_slots.connect(CL_Mouse::sig_move(), this, &Swatter::OnMouseMove);

	SetType(C_TYPE_SWATTER);
	m_sprite = new CL_Sprite("swatter_small", GetApp()->GetResourceManager());
	m_vecLastMousePos = CL_Point(0,0);

	g_pSwatter = this; //don't try this ugliness at home!
}

Swatter::~Swatter()
{
	g_pSwatter = NULL;
}

CL_Vector2 ClipToRect(CL_Vector2 v, const CL_Rect &r)
{

	v.x = min(v.x, r.right);
	v.x = max(v.x, r.left);

	v.y = min(v.y, r.bottom);
	v.y = max(v.y, r.top);

	return v;
}

void Swatter::OnMouseMove(const CL_InputEvent &key)
{

	/*
	POINT winPt;
	GetCursorPos(&winPt);
	CL_Point origPt = CL_Point(winPt.x, winPt.y);;
	*/

	CL_Point origPt = key.mouse_pos;

	CL_Point pt = origPt - m_vecLastMousePos;

	switch (m_movementMode)
	{
	case C_MOVE_RIGHT_ONLY:
		if (pt.x < 0) pt.x = 0;
		break;

	case C_MOVE_LEFT_ONLY:
		if (pt.x > 0) pt.x = 0;
		break;
	}
	m_vPosition += CL_Vector2(pt.x, pt.y);

	//printf("adding %d, %d", pt.x, pt.y);
	//clip it?


	CL_Mouse::set_position(GetScreenX/2, GetScreenY/2);
	m_vecLastMousePos = CL_Point(GetScreenX/2, GetScreenY/2);

}

void Swatter::OnButtonDown(const CL_InputEvent &key)
{
	if (key.id == CL_MOUSE_LEFT)
	{
		printf("LMB!");
	}
}


void Swatter::Update(float step)
{
	m_vPosition = ClipToRect(m_vPosition, m_rectLimit);

	
		switch (m_movementMode)
		{
		case C_MOVE_LEFT_ONLY:
			if (m_vPosition.x < (C_EDGE_BORDER + C_SWAT_FINISH_PADDING))
			{

				//done with side
				GetGameLogic->CalculateSwipeScore();

				if (GetGameLogic->m_wavesLeft > 0)
				GetGameLogic->GetMessageDispatcher()->SendMsg(C_MESSAGE_PREPARE_RIGHT,0);
				SetMovementMode(C_MOVE_ANYWHERE);
			}
			break;

		case C_MOVE_RIGHT_ONLY:

			if (m_vPosition.x > (GetScreenX-C_EDGE_BORDER) - C_SWAT_FINISH_PADDING)
			{
				//done with side
				GetGameLogic->CalculateSwipeScore();
				if (GetGameLogic->m_wavesLeft > 0)
				GetGameLogic->GetMessageDispatcher()->SendMsg(C_MESSAGE_PREPARE_LEFT,0);
				SetMovementMode(C_MOVE_ANYWHERE);
			}
			break;
		}
	
	Entity::Update(step);


}