//Copyright (C) 2007 SiegeLord
//See ReadMe.txt and License.txt for copying information

#include "plasma.h"
#include "explosion.h"
#include "ship.h"
#include "shipregistry.h"
#include "thruster.h"

extern SObjectEx* g_obRootObject;

SPlasma::~SPlasma()
{
	thruster->target_object = 0;
}

int SPlasma::Handle()
{
	life += g_fDelta;
	vector2d cur_pos = GetGlobalPosition();

	if(life > max_life)//ran out of fuelz
	{
		dead = true;
		thruster->target_object = 0;
		CreateExplosion(cur_pos, 0.3, 0xff00ff00);
	}

	if(target_ship_id > -1)
	{
		SShip* ship = GetShipByID(target_ship_id);
		if(ship)
		{
			if(ship->global_bbox.PointTest(cur_pos))//we hit the ship
			{
				dead = true;
				ship->Damage(min_damage, max_damage);
				thruster->target_object = 0;
				CreateExplosion(cur_pos, 0.3, 0xff00ff00);
				return 0;
			}
			target_loc = ship->GetGlobalPosition();
		}
		else//target was lost
			target_ship_id = -1;
	}
	vector2d dir = target_loc - cur_pos;

	if(dir.GetLengthSQ() < 2 * velocity.GetLengthSQ() * g_fDelta * g_fDelta)//we are at target
	{
		dead = true;
		thruster->target_object = 0;
		CreateExplosion(cur_pos, 0.3, 0xff00ff00);
		return 0;
	}

	position += velocity * g_fDelta;

	SetPosition(position.x, position.y);
	SetRotation(atan2f(dir.y, dir.x));

	return 0;
}

void SPlasma::Draw()
{
	SetModelMatrix(net_transform);

	DrawModeAdd();

	DrawBitmap(image, -image->w / 2, -image->h / 2, -10);

	DrawModeSolid();

	SetModelMatrix(g_trIdentity);
}

SPlasma* CreatePlasma(SObject* parent, vector2d& start_pos, vector2d& ini_vel, vector2d& destination, int ship_id)
{
	SPlasma* plasma = new SPlasma();
	InitObject(plasma, parent);

	plasma->target_ship_id = ship_id;
	plasma->target_loc = destination;

	plasma->max_life = 5.0f;

	plasma->life = 0;

	plasma->min_damage = 10.0f;
	plasma->max_damage = 10.0f;

	plasma->SetPosition(start_pos.x, start_pos.y);

	plasma->velocity = ini_vel;

	plasma->thruster = CreateThrusterParticleHolder(g_obRootObject, plasma, FindBitmap("part.tga"), 0xff00ff00);

	plasma->thruster->throttle = 1;
	plasma->thruster->random_vel_y = 0;
	plasma->thruster->SetRotation(AL_PI);

	plasma->image = FindBitmap("plasma.tga");

	return plasma;
}
