package  {
	import flash.display.MovieClip
	import flash.events.MouseEvent;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import flash.display.Sprite;
	
	public class MyGame extends MovieClip
	{
		public static const ENEMY_DISTANCE = 180;
		
		private var _player:Player;
		private var _enemies:Vector.<Enemy> = new Vector.<Enemy>;
		private var _bullets:Vector.<Bullet> = new Vector.<Bullet>;
		
		private var _enemyTimer:Timer;

		public function MyGame() 
		{
			_player = new Player();
			_player.x = stage.stageWidth/2;
			_player.y = stage.stageHeight/2;
			addChild(_player);
			
			_enemyTimer = new Timer(1000);
			_enemyTimer.start();
			_enemyTimer.addEventListener(TimerEvent.TIMER, addEnemy);
			
			stage.addEventListener(MouseEvent.MOUSE_MOVE, rotatePlayer);
			stage.addEventListener(Event.ENTER_FRAME, updateGame);
			stage.addEventListener(MouseEvent.CLICK, fireBullet);
		}
		
		public function rotatePlayer(e:MouseEvent)
		{
			var angle = Math.atan2(mouseY - _player.y, mouseX - _player.x);
			angle = angle * 180 / Math.PI;
			_player.rotation = angle;
		}
		
		public function addEnemy(e:TimerEvent)
		{
			var randAngle = Math.random() * 2*Math.PI;
			
			var enemy = new Enemy();
			enemy.x = ENEMY_DISTANCE * Math.cos(randAngle) + stage.stageWidth/2;
			enemy.y = ENEMY_DISTANCE * Math.sin(randAngle) + stage.stageHeight/2;
			_enemies.push(enemy);
			addChild(enemy);
			
			var oppAngle = randAngle - Math.PI;
			enemy.vx = enemy.speed * Math.cos(oppAngle);
			enemy.vy = enemy.speed * Math.sin(oppAngle);
			
		}
		
		public function updateGame(e:Event)
		{
			for( i = 0; i < _bullets.length; i++)
			{
				_bullets[i].update();
			}
			
			for(var i = 0; i < _enemies.length; i++)
			{
				_enemies[i].update();
				
				if(_enemies[i].hitTestObject(_player))
				{
					removeChild(_enemies[i]);
					_enemies.splice(i,1);
					i--;
					break;
				}
				
				for(var j = 0; j < _bullets.length; j++)
				{
					if(_enemies[i].hitTestObject(_bullets[j]))
					{
						removeChild(_enemies[i]);
						_enemies.splice(i,1);
						removeChild(_bullets[j]);
						_bullets.splice(j,1);
						i--;
						j--;
						break;
					}
				}
			}
		}
		
		public function fireBullet(e:Event)
		{
			var bullet = new Bullet();
			bullet.x = stage.stageWidth/2;
			bullet.y = stage.stageHeight/2;
			
			var angle = _player.rotation / 180 * Math.PI;
			bullet.vx = bullet.speed * Math.cos(angle);
			bullet.vy = bullet.speed * Math.sin(angle);
			addChild(bullet);
			_bullets.push(bullet);
		}

	}
	
}
