package com.indindi.Text 
{
    import flash.display.*;
    import flash.geom.*;
	
	public class DText 
	{
        public static const LEFT:int = 0;
        public static const RIGHT:int = 1;
        public static const CENTER:int = 2;
        
        private static const DEFAULT_CHAR:Number = '?'.charCodeAt(0);
        private static const NEW_LINE:Number = '\n'.charCodeAt(0);

        private static var i:int;

		// Largeur d'un charactère
		private var LgChar:int = 0;
		
		// Hauteur d'un caractère
		private var HgChar:int = 0;
		
		// Espacement entre les caractères
		private var EspChars:int = 0;

		// La planche de lettres		
		private var chars:BitmapData;

        private var CHAR_RECTS:Object = new Object();	
		
		// L, H, Spacing
		public function DText(m_chars:BitmapData, LgtChar:int,HgtChar:int,SpcChars:int):void
		{
			chars = m_chars;
			LgChar = LgtChar;
			HgChar = HgtChar;
			EspChars = SpcChars;

			for (i = 32; i < 161; i++)
                CHAR_RECTS[i] = new Rectangle(((i - 32) % (LgChar+EspChars)) * (LgChar+EspChars), (int)((i - 32) / HgChar) * HgChar, LgChar, HgChar);
        }
        
        public function draw(buffer:BitmapData, text:String,  x:int = 0, y:int = 0, align:int = DText.LEFT):void 
		{
            var lines:Array = text.split('\n');
            for each(var line:String in lines) {
                if (align == LEFT)
                    drawLine(buffer, line, x, y, chars);
                else if (align == RIGHT)
                    drawLine(buffer, line, x - line.length * 8, y, chars);
                else // CENTER
                    drawLine(buffer, line, x - line.length * 8 / 2, y, chars);
                y += 13;
            }
        }
        
        private function drawLine(buffer:BitmapData, text:String, x:int, y:int, chars:BitmapData ):void 
		{
            var p:Point = new Point(x, y);
            var len:int = text.length;
            for (var n:int = 0; n < len; n++) {
                var c:Number = text.charCodeAt(n);
                if (c > 160 || c < 32)
                    c = DEFAULT_CHAR;
                buffer.copyPixels(chars, CHAR_RECTS[c], p, null, null, true);
                p.x += 8;
            }
        }
    }
}