package  
{
	import adobe.utils.ProductManager;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Point;
	import manager.Manager;
	/**
	 * ...
	 * @author Team Alfajor
	 */
	public class Meteor extends Entity
	{	
		static private const COLLISION_RADIUS:Number = 50;
		
		private var mc:MovieClip;
		private var speed:Point;
		private var gravityAcceleration:Point;
		private var hitAcceleration:Point;
		private var initialVelocity:Number;
		private var state:String;
		
		public function Meteor(pos:Point, velocity:Number) 
		{
			mc = Main.instance.mediaLibrary.getMovieClip("Meteor");
			Main.instance.getUniverseMC().addChild(mc);
			
			mc.x = pos.x;
			mc.y = pos.y;
			
			gravityAcceleration = getVectorTowardEarth();;
			gravityAcceleration.normalize(10);
			
			speed = getVectorTowardEarth();
			speed.normalize(velocity);
			
			hitAcceleration = new Point(0, 0);
					
			initialVelocity = velocity;			
		}		
		
		
		override protected function mUpdate(aTime:Number):void 
		{
			super.mUpdate(aTime);
			mc.x += speed.x * aTime;
			mc.y += speed.y * aTime;			
			
			var netAcceleration:Point = gravityAcceleration.add(hitAcceleration);
			
			speed.x += netAcceleration.x * aTime;
			speed.y += netAcceleration.y * aTime;
			
			if (collidesWithEarth()) {
				mUnregister();
				SoundMaster.playFX("explosion");				
				createEarthExplosion();
				Main.instance.meteorHitsEarth();
			}
			
			if (distanceFromEarth() > 1000) {
				mUnregister();				
			}
			
			var collidingMeteor:Meteor = Main.instance.getMeteoriteSpawner().getMeteorManager().getCollidingMeteor(this);
			if (collidingMeteor != null) {
				explode();				
				collidingMeteor.explode();
				createEarthExplosion();	
			}
		}
		
		
		public function explode():void 
		{
			mUnregister();
		}
		
		
		
		override public function mDestroy():void 
		{
			super.mDestroy();
			
			Main.instance.getUniverseMC().removeChild(mc);
		}

		
		public function takeHit(bulletPos:Point):void 
		{			
			SoundMaster.playFX("explosion");
			
			var accelAwayFromEarth:Point = Utils.getOppositeVector(getVectorTowardEarth());
			accelAwayFromEarth.normalize(600);
			
			var accelAwayFromBullet:Point = getPos().subtract(bulletPos);
			accelAwayFromBullet.normalize(900);			
			
			if (Point.distance(getPos(), Main.instance.player.getPos()) < 50) {
				accelAwayFromBullet = new Point(0, 0);				
			}
			
			hitAcceleration = accelAwayFromBullet.add(accelAwayFromEarth);
			hitAcceleration.normalize(1500);
			
			schedule(onHitAccelerationEnd, 0.1);			
		}
		
		
		private function onHitAccelerationEnd(e:Event):void 
		{
			hitAcceleration = new Point(0, 0);
		}
		
		
		public function collidesWith(entity:Entity):Boolean
		{
			var distance:Number = Point.distance(getPos(), entity.getPos());
			
			return distance < COLLISION_RADIUS;
		}
		
		
		override public function getMC():MovieClip 
		{
			return mc;
		}
	}

}