package classes.matuto.utils.display
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;

	public class Resizer
	{
		
		public static const NONE	:int = 0;
		public static const TOP 	:int = 1;
		public static const MIDDLE 	:int = 2;
		public static const BOTTOM 	:int = 4;
		public static const LEFT 	:int = 8;
		public static const CENTER 	:int = 16;
		public static const RIGHT 	:int = 32;
		
		public static function resize(target :DisplayObject, reference :*, fit :Boolean = false, align :Number = 0, force :Boolean = true) :void
		{
			if(target is Bitmap) Bitmap(target).smoothing = true;
			
			var _width 	:Number;
			var _height	:Number;
			
			_width  = reference.width;
			_height = reference.height;
			
			var pct_x :Number = _width/target.width;
			var pct_y :Number = _height/target.height;
			
			if( (!fit && pct_x>pct_y) || (fit && pct_x<pct_y) )
			{
				target.width  *= pct_x;
				target.height *= pct_x;
			}else{
				target.width  *= pct_y;
				target.height *= pct_y;
			}
			
			var h :int = match( align, LEFT, CENTER, RIGHT );
			var v :int = match( align, TOP, MIDDLE, BOTTOM );
			
			var _x :Number = 0;
			var _y :Number = 0;
			
			if(align){
				switch(h){
					case LEFT:
						_x = reference.x;
						break;
					case CENTER:
						_x = reference.x + (reference.width*.5 - target.width*.5);
						break;
					case RIGHT:
						_x = reference.x + reference.width - target.width;
						break;
				}
				
				switch(v){
					case TOP:
						_y = reference.y;
						break;
					case MIDDLE:
						_y = reference.y + (reference.height*.5 - target.height*.5);
						break;
					case BOTTOM:
						_y = reference.y + reference.height - target.height;
						break;
				}
				
				target.x = _x;
				target.y = _y;
			}
			
		}
		
		private static function match( value : int, ... options : Array ) : int
		{
			var option : int;
			
			while ( option = options.pop() )
			{
				if ( ( value & option ) == option )
				{
					return option;
				}
			}
			
			return 0;
		}
		
	}
}