package  
{
	import enemies.Enemy;
	import engine.Collisions;
	import engine.MathExt;
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.geom.Point;
	import interfaces.IGameObject;
	
	/**
	 * ...
	 * @author beisik
	 */
	public class Bullet extends Sprite implements IGameObject
	{
		[Embed(source = "../lib/sprites/bullet.png")] private const embedBullet: Class;
		[Embed(source = "../lib/sprites/bullet_trace.png")] private const embedBulletTrace: Class;
		
		public var radius: Number;		
		public var byPlayer: Boolean;
		
		private var _velocity: Point;
		private var _speed: Number;
		
		public var dead: Boolean = false;
		private var _deathTimer: Number = 0.5;
		private var _traceSprite: Sprite;
		
		public function Bullet(x: Number, y: Number, player: Boolean, vx: Number, vy: Number) 
		{			
			this.x = x;
			this.y = y;
			
			radius = 5;
			
			/*if (!player)
				graphics.beginFill(0xFFFFFF);
			else
				graphics.beginFill(0);
			graphics.drawRect(-radius, -radius, radius * 2, radius * 2);
			graphics.endFill();*/
			bitmap = new embedBulletTrace();
			bitmap.x -= bitmap.width;
			bitmap.y -= bitmap.height / 2;
			_traceSprite = new Sprite();
			_traceSprite.addChild(bitmap);
			_traceSprite.scaleX = 0;
			addChild(_traceSprite);
			
			var bitmap: Bitmap = new embedBullet();
			bitmap.x -= bitmap.width / 2;
			bitmap.y -= bitmap.height / 2;
			addChild(bitmap);
			
			byPlayer = player;	
			this._velocity = new Point(vx, vy); 
			_speed = 350;
			
			if (!byPlayer)
				scaleX = -1;
		}
		
		/* INTERFACE interfaces.IGameObject */
		
		public function Update(dt: Number): void
		{				
			if (dead)
			{
				_traceSprite.alpha = _deathTimer * 2;
				_deathTimer -= dt;
				if (_deathTimer <= 0)
					World.world.bulletsList.remove(this);
				return;
			}
			
			if (_traceSprite.scaleX < 1)
				_traceSprite.scaleX += dt * 1.5;
			
			x += _velocity.x * _speed * dt;
			y += _velocity.y * _speed * dt;
			
			if (byPlayer)
			{
				for each (var e: Enemy in World.world.enemiesList.objects)
					if (Collisions.intersectCircleCircle(x, y, radius, e.x, e.y, e.radius))
					{
						e.GetDamage();
						die();
						return;
					}
			}
			else
				if (Collisions.intersectCircleCircle(x, y, radius, World.world.hero.x, World.world.hero.y, World.world.hero.radius))
				{
					World.world.hero.GetDamage();
					die();
					return;
				}
				
			for each (var b: Bullet in World.world.bulletsList.objects)
				if (!b.dead && b != this && b.byPlayer != byPlayer)
					if (Collisions.intersectCircleCircle(x, y, radius * 2, b.x, b.y, b.radius * 2))
					{
						b.die();
						die();
						return;
					}
				
			// вылетела за границы экрана
			if (x > (Game.screenWidth + radius) || x < -radius || y < -radius || y > (Game.screenHeight + radius)) 
				die();
		}
		
		private function die(): void
		{
			dead = true;
			removeChildAt(1);
		}
		
	}

}