#include "ball.h"
#include "mesh.h"
#include <d3dx9shape.h>

Ball::Ball(LPDIRECT3DDEVICE9 CreationDevice, float BallRadius, int Slices, int Stacks, DWORD Color)
{
	BallMesh = new Mesh();
	LPD3DXMESH NewMesh;
    
	Radius = BallRadius;

	D3DXCreateSphere(CreationDevice, Radius, 10, 10, &NewMesh, NULL);
	BallMesh->SetD3DXMesh(NewMesh);

	D3DMATERIAL9 NewMaterial;
	memset(&NewMaterial,0, sizeof(NewMaterial));
	NewMaterial.Ambient.a = 1;
	NewMaterial.Ambient.b = 0;
	NewMaterial.Ambient.r = 1;
	NewMaterial.Ambient.g = 0;
	NewMaterial.Diffuse = NewMaterial.Ambient;
	BallMesh->SetMaterials(1, &NewMaterial);

	Mass = 5;

	Velocity = D3DXVECTOR3(0,0,0);

	CollisionCount = 0;
}

Ball::~Ball()
{
	delete BallMesh;
}

Ball::Ball()
{
	BallMesh = NULL;
	
}

void Ball::GetMeshes(Mesh** MeshArray)
{
	MeshArray[0] = BallMesh;
}

int Ball::GetMeshCount()
{
	return 1;
}

D3DXVECTOR3 Ball::GetGroundContactPoint()
{
    D3DXVECTOR3 Result;
	Result = Position;
	Result.z -= Radius;
	return Result;
}

unsigned int Ball::GetAction(float TimeStep, Msg** SentMsgs)
{
	D3DXVECTOR3 NewPosition = GetUpdatedPosition(TimeStep);
	//If the object is moving..
	if(D3DXVec3LengthSq(&Velocity)>0)
	{
		MoveMsg* MoveRequest = new MoveMsg();
		MoveRequest->Sender = this;
		MoveRequest->Reciever = NULL; //we don't know; whoever is listening
		MoveRequest->MovementAmount = NewPosition - Position;
        SentMsgs[0] = MoveRequest;
		return 1;
	}
	else
	{
		return 0;
	}
}
unsigned int Ball::SendMsg(Msg* RecievedMsg, Msg** SentMsgs)
{
	//The only thing we are listening for right now is a moveok msg
	if(RecievedMsg->Type == mMoveOK)
	{
		//Set the object's position to what the ok messages says to
		Position += (static_cast<MoveOKMsg*>(RecievedMsg))->MovementAmount;
		return 0;
	}
	else if(RecievedMsg->Type == mGroundCollision)
	{
		//here's where we do the math
		D3DXVECTOR3 Normal = (static_cast<GroundCollisionMsg*>(RecievedMsg))->Normal;
		Force CollisionForce;
		CollisionForce.Duration = .001;
		CollisionForce.ForceVector = .9*-2000*Mass*D3DXVec3Dot(&Velocity, &Normal)*Normal;
		//CollisionForce.ForceVector = 200*Mass*D3DXVECTOR3(0,0,1);
		AddConstantForce(CollisionForce);
		CollisionCount++;
		if(CollisionCount>50)
		{
            //MessageBox(NULL, "test", NULL, NULL);
		}
		return 0;
	}
	else
	{
		return 0;
	}
}
