package net.phatcode.rel;

import net.phatcode.rel.math.Vector2D;

public class TurretFactory
{
	public static final int OUT_OF_BOUNDS = -1;
	
	private Turret[] turrets;
	
	private int activeTurrets = 0;
	
	public TurretFactory( int size )
	{
		
		turrets = new Turret[size];
		int s = turrets.length;
		for( int i = 0; i < s; i++ )
		{
			turrets[i] = new Turret();
		}
		
	}
	
	public Turret spawn( BulletPattern bulletPattern,
					     float x,
					     float y,
					     float angle,
				   	     float minAngle,
				   	   	 float maxAngle,
				   	   	 float angleDelta,
				   	   	 int angleDirection,
				   	   	 boolean seekPlayer,
				   	   	 TurretBehavior rotateBehavior,
				   	   	 TurretBehavior fireBehavior )
	{
		
		int size = turrets.length;
		for( int i = 0; i < size; i++ )
		{
			if( !turrets[i].isActive() )
			{
				Turret cannon = turrets[i];
				
				cannon.setPattern( bulletPattern );
				
				cannon.setBehaviorInfo( angle,
							   	 		minAngle,
							   	 		maxAngle,
							   	 		angleDelta,
							   	 		angleDirection,
							   	 		seekPlayer,
							   	 		rotateBehavior,
							   	 		fireBehavior );
				
				cannon.setPosition( x, y );
				
				cannon.setActive( true );
				
				return cannon;
			
			}
		}
			
		return null;
		
	}
	
	public int getSize()
	{
		return turrets.length;
	}
	
	public int getActiveTurrets()
	{
		return activeTurrets;
	}
	
	public Turret getTurret( int index )
	{
		return turrets[index];
	}
	
	public int getAvailableTurretIndex()
	{
		int size = turrets.length;
		for( int i = 0; i < size; i++ )
		{
			Turret t = turrets[i];
			if( !t.isActive() ) return i;
		}
		return OUT_OF_BOUNDS;
	}
	
	
	public void destroyAllTurrets()
	{
		int size = turrets.length;
		for( int i = 0; i < size; i++ )
		{
			Turret t = turrets[i];
			
			if( t.isActive() )
			{
				t.kill() ;
			}
		}
		
	}
	
	public void killAllTurrets()
	{
		int size = turrets.length;
		for( int i = 0; i < size; i++ )
		{
			Turret t = turrets[i];
			
			if( t.isActive() )
			{
				t.kill() ;
			}
		}
	}
	
	public void updateTurrets( BulletFactory bulletFactory, Vector2D playerShipPosition )
	{
		activeTurrets = 0;
		int size = turrets.length;
		for( int i = 0; i < size; i++ )
		{
			Turret t = turrets[i];
			
			if( t.isActive() )
			{
				t.update( bulletFactory, playerShipPosition );
				activeTurrets++;
			}
		}
		
	}
	
	
}
