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

#include "ionbeam.h"
#include "weapon.h"
#include "ship.h"
#include "shipregistry.h"
#include "thruster.h"

extern SObjectEx* g_obRootObject;

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

int SIonBeam::Handle()
{
	life += g_fDelta;
	
	if(life > max_life || weapon == 0)//ran out of fuelz
	{
		dead = true;
		thruster->target_object = 0;
		return 0;
	}

	if(target_ship_id > -1)
	{
		SShip* ship = GetShipByID(target_ship_id);
		if(ship)
		{
			vector2d ship_pos = ship->GetGlobalPosition();
			vector2d weapon_pos = weapon->GetGlobalPosition();
			vector2d dir = g_vecI;
			weapon->net_transform.RotateVector(&dir);
			
			vector2d actual_dir = ship_pos - weapon_pos;
			float len = actual_dir.GetLength();
			float ang = acosf(actual_dir.DotProduct(dir) / len / dir.GetLength());
			if(fabs(ang) < 0.05)//we seem to be pointing at it
			{
				target_range = len;//get the new range and damage it a bit
				ship->Damage(min_damage, max_damage, g_fDelta / max_life);
				if(thruster)
					thruster->throttle = 2;
			}
			else
			{
				if(thruster)
					thruster->throttle = 0;
			}
		}
		else//target was lost
		{
			target_ship_id = -1;
			if(thruster)
				thruster->throttle = 0;
		}
	}
	if(thruster)
		thruster->SetPosition(target_range + 5, 0);

	return 0;
}

void SIonBeam::Draw()
{
	if(!weapon)
		return;
	SetModelMatrix(weapon->net_transform);
	
	float offset = image->w * 5.0f * life / max_life;

	DrawModeAdd();

	SetColor(0xffff0000);

	DrawBitmapTiled(image, 5, -image->h / 2, -10, target_range, image->h, -offset, 0);
	
	SetColor(0xffffffff);
	
	DrawBitmapTiled(image, 5, -image->h / 2, -10, target_range, image->h, -offset, 0);

	DrawModeSolid();

	SetModelMatrix(g_trIdentity);
}

SIonBeam* CreateIonBeam(SObject* parent, SWeapon* source_weapon, float target_range, int ship_id)
{
	SIonBeam* beam = new SIonBeam();
	InitObject(beam, parent);

	beam->target_ship_id = ship_id;
	beam->target_range = target_range;

	beam->max_life = 2.0f;

	beam->life = 0;

	beam->min_damage = 10.0f;
	beam->max_damage = 20.0f;
	
	beam->weapon = source_weapon;

	beam->thruster = CreateThrusterParticleHolder(g_obRootObject, source_weapon, FindBitmap("part.tga"), 0xffff0000);

	beam->thruster->throttle = 0;
	beam->thruster->random_vel_y = 20;
	beam->thruster->random_vel_x = 20;
	beam->thruster->SetRotation(AL_PI);
	beam->thruster->SetPosition(target_range + 5, 0);

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

	return beam;
}

