package game.GameMain
{
	import flinjin.events.FlinjinSpriteEvent;
	import flinjin.Flinjin;
	import flinjin.graphics.Layer;
	import flinjin.graphics.Sprite;
	import game.GameMain.LevelTiles.LevelTile;
	import game.GameMain.LevelTiles.Tile1;
	import game.GameMain.LevelTiles.Tile2;
	import game.GameMain.LevelTiles.Tile3;
	import game.GameMain.LevelTiles.Tile4;
	import game.GameMain.LevelTiles.TileBottom;
	
	/**
	 * ...
	 * @author Michael Miriti
	 */
	public class LevelScroll extends Layer
	{
		private var _tiles:Vector.<LevelTile> = new Vector.<LevelTile>;
		private var _nextTileY:Number = 0;
		
		override public function Dispose():void
		{
			//super.Dispose();
		}
		
		/**
		 * map pixel
		 *
		 * @param	nx
		 * @param	ny
		 * @return
		 */
		public function getMapPixel(nx:int, ny:int):uint
		{
			for (var i:int = 0; i < _tiles.length; i++)
			{
				if ((ny >= _tiles[i].y) && (ny < _tiles[i].y + _tiles[i].height) && (nx >= _tiles[i].x) && (nx < _tiles[i].x + _tiles[i].width))
				{
					var px:uint = _tiles[i].getPixelAt(nx - _tiles[i].x, ny - _tiles[i].y);
					if (px != 0)
						return px;
				}
			}
			return 0;
		}
		
		override public function Move():void
		{
			for (var i:int = _tiles.length - 1; i >= 0; i--)
			{
				if (_tiles[i].y + _layerShift.y > Flinjin.sceneHeight)
				{
					deleteSprite(_tiles[i]);
					_tiles.splice(i, 1);
				}
			}
			super.Move();
		}
		
		public function addTile(t:LevelTile, hasOwnCoords:Boolean = false):void
		{
			if (!hasOwnCoords)
			{
				t.y = _nextTileY - t.height;
				_nextTileY = _nextTileY - t.height;
			}
			_tiles.push(t);
			addSprite(t);
		}
		
		public function addRandomTile():void
		{
			var rndTile:LevelTile;
			
			switch (Math.floor(4 * Math.random()))
			{
				case 0: 
					rndTile = new Tile1();
					break;
				case 1: 
					rndTile = new Tile2();
					break;
				case 2: 
					rndTile = new Tile3();
					break;
				case 3: 
					rndTile = new Tile4();
					break;
			}
			
			addTile(rndTile);
			rndTile.InitMobs();
		}
		
		public function LevelScroll()
		{
			super(Flinjin.sceneWidth, Flinjin.sceneHeight);
			
			EnableClip = true;
			
			addEventListener(FlinjinSpriteEvent.ADDED_TO_LAYER, onAddedToLayer);
		
		}
		
		private function onAddedToLayer(e:FlinjinSpriteEvent):void
		{
			var _bottm:TileBottom = new TileBottom();
			_nextTileY = 640;
			addTile(_bottm);
			addRandomTile();
			addRandomTile();
		}
	}

}