package  {
	import flash.display.MovieClip;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import djarts.core.CacheManager;
	
	public class ChunkedGraphic extends MovieClip
	{
		
		public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512)
		{
			this.name = clip.name;
			var r:Rectangle = clip.getBounds(clip);
			//assuming for very large graphics that the bounds will work...
			if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048);
			
			var rect = new Rectangle(0,0,chunkSize, chunkSize);
			var xChunks = Math.ceil(clip.width / chunkSize);
			var yChunks = Math.ceil(clip.height / chunkSize);

			var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize);
			var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize);

			if (finalChunkWidth == 0) finalChunkWidth = chunkSize;
			if (finalChunkHeight == 0) finalChunkHeight = chunkSize;
			
			for (var y = 0; y < yChunks; y++)
			{
				for (var x = 0; x < xChunks; x++)
				{

					var chunkWidth = chunkSize;
					var chunkHeight = chunkSize;
					if (y == yChunks - 1) chunkHeight = finalChunkHeight;
					if (x == xChunks - 1) chunkWidth = finalChunkWidth;
					
					var chunk:MovieClip = new MovieClip();
					var trans:Matrix = new Matrix();
					trans.tx = -x * chunkSize - r.left;
					trans.ty = -y * chunkSize - r.top;
					var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0);
					var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData);
					chunkBitmapData.draw(clip, trans);
					chunk.addChild(chunkBitmap);
					chunk.x = -trans.tx;
					chunk.y = -trans.ty;
					this.addChild(chunk);
				}
			}

			this.x = clip.x;
			this.y = clip.y;
			
		}

	}
	
}
