package enemies 
{
	import engine.MathExt;
	import engine.Utils;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.filters.ColorMatrixFilter;
	import flash.geom.Point;
	import interfaces.IGameObject;
	
	/**
	 * ...
	 * @author Fiodar Paulavets
	 */
	public class Enemy extends Sprite implements IGameObject 
	{
		protected var _clip: MovieClip;
		protected var _maskClip: MovieClip;
		private var damaged: Number = 0;
		
		protected var _velocity: Point = new Point();
		protected var target: Point = null;
		protected var _speed: Number;
		
		public var life: int;
		public var radius: Number;
		
		public function Enemy(clip: Class, width: Number) 
		{
			_clip = new clip();
			_clip.scaleX = _clip.scaleY = width / _clip.width;
			//_clip.x -= _clip.width / 2;
			//_clip.y -= _clip.height / 2;
			addChild(_clip);
			_clip.play();
			
			_maskClip = new clip();
			_maskClip.scaleX = _maskClip.scaleY = width / _maskClip.width;
			//_maskClip.x -= _maskClip.width / 2;
			//_maskClip.y -= _maskClip.height / 2;
			var matrix:Array = new Array();
            matrix = matrix.concat([1, 1, 1, 0, 0]); // red
            matrix = matrix.concat([1, 1, 1, 0, 0]); // green
            matrix = matrix.concat([1, 1, 1, 0, 0]); // blue
            matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha
			var filter: ColorMatrixFilter = new ColorMatrixFilter(matrix);
			_maskClip.filters = [filter];
			_maskClip.visible = false;
			addChild(_maskClip);
			_maskClip.play();
		}
		
		/* INTERFACE interfaces.IGameObject */
		
		public function Update(dt:Number):void 
		{
			// перемещение
			if (target == null)
			{
				x += _velocity.x * _speed * dt;
				y += _velocity.y * _speed * dt;
			}
			else
			{
				x = Utils.Aspire(x, target.x, Math.abs(_velocity.x) * dt);
				y = Utils.Aspire(y, target.y, Math.abs(_velocity.y) * dt);
			}
			
			// столкновение с игроком
			if (MathExt.Distance(x, y, World.world.hero.x, World.world.hero.y) <= radius + World.world.hero.radius)
			{
				World.world.hero.GetDamage();
				die(true);
				return;
			}
			
			// мигание
			if (damaged > 0)
			{
				damaged -= dt;
				_maskClip.alpha -= dt * 2;
				if (damaged <= 0)
					_maskClip.visible = false;
			}
			
			if (x < -_clip.width * 2 || x > Game.screenWidth + _clip.width * 2 || y < -_clip.height * 2 || y > Game.screenHeight + _clip.height * 2)
				die(false);
		}
		
		public function GetDamage(): void
		{
			if (x > Game.screenWidth + _clip.width / 2)
				return;
			life--;
			damaged = 0.5;
			_maskClip.alpha = 1;
			_maskClip.visible = true;
			if (life <= 0)
				die(true);
		}
		
		protected function die(explode: Boolean): void
		{
			if (explode)
			{
				World.world.particlesList.add(new Explosion(x, y));
				Sounds.manager.playSound("explosion");
			}
			World.world.enemiesList.remove(this);
		}
		
	}

}