package entities 
{
	import display.states.GameState;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;
	import starling.display.Sprite;
	import starling.events.Event;
	
	/**
	 * ...
	 * @author RedMaster
	 */
	public class Manager extends Sprite 
	{
		private var _entities:Vector.<Entity> = new Vector.<Entity>();
		private var _viewPort:Rectangle = new Rectangle();
		public var char:Rectangle = new Rectangle();
		
		private var _isGrowling:Boolean = false;
		private var _monsterSoundTimer:Timer = new Timer(2000);
		
		public function Manager()
		{
			_viewPort.width = C.screen.width;
			_viewPort.height = C.screen.height;
			
			_monsterSoundTimer.addEventListener(TimerEvent.TIMER, onTimer);
			_monsterSoundTimer.start();
		}
		
		public function addEntity(entity:Entity):void
		{
			_entities.push(entity);
		}
		public function addEntities(entities:Vector.<Entity>):void
		{
			_entities = _entities.concat(entities);
		}
		public function clearEntities():void
		{
			_entities = null;
			_entities = new Vector.<Entity>();
		}
		
		public function setPosition(x:Number, y:Number):void
		{
			_viewPort.x = x;
			_viewPort.y = y;
		}
		
		public function update():void
		{
			for (var i:uint = 0; i < _entities.length; i++)
			{
				var ent:Entity = _entities[i];
				if (!_viewPort.intersects(ent.aabb) && ent.name != "Balrog")
				{
					removeChild(ent.display);
					continue;
				}
				ent.player = char;
				ent.update();
				ent.display.x = ent.x - _viewPort.x + ent.display.pivotX;
				ent.display.y = ent.y - _viewPort.y + ent.display.pivotY;
				addChild(ent.display);
				if (ent.aabb.intersects(char))
				{
					Log.log(this, "Monster or Balrog hit player");
					Game.Playing.dispatchEventWith(GameState.DEATH);
					return;
				}
			}
		}
		
		private function onTimer(e:TimerEvent):void
		{
			for (var i:uint = 0; i < _entities.length; i++)
			{
				var ent:Entity = _entities[i];
				if (_viewPort.intersects(ent.aabb) && Math.random() > 0.7)
				{
					var name:String = "";
					if (ent.name == "Monster" && !_isGrowling)
					{
						_isGrowling = true;
						(ent as Enemy).growl().addEventListener(flash.events.Event.SOUND_COMPLETE, onSoundComplete);
						continue;
					}
					if (ent.name == "Balrog") (ent as Enemy).growl();
				}
			}
		}
		
		private function onSoundComplete(e:flash.events.Event):void
		{
			_isGrowling = false;
		}
		
		public function destroy():void
		{
			_entities = null;
			if(_monsterSoundTimer) _monsterSoundTimer.stop();
			_monsterSoundTimer = null;
		}
		
		public function get quantity():uint
		{
			return _entities.length;
		}
	}
}