package pdf 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.geom.Matrix;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	//import isrg.goal.data.GameState;
	//import isrg.goal.display.Images;
	//import isrg.goal.display.MediaDisplayFrame;
	//import isrg.goal.screens.Feedback;
	//import isrg.goal.screens.Gameplay;
	//import isrg.goal.screens.PageFramework;
	import org.alivepdf.colors.RGBColor;
	import org.alivepdf.display.Display;
	import org.alivepdf.fonts.FontFamily;
	import org.alivepdf.fonts.Style;
	import org.alivepdf.images.ImageFormat;
	import org.alivepdf.images.ResizeMode;
	import org.alivepdf.layout.Orientation;
	import org.alivepdf.layout.Size;
	import org.alivepdf.layout.Unit;
	import org.alivepdf.pages.Page;
	import org.alivepdf.pdf.PDF;
	import org.alivepdf.saving.Method;
	
	/**
	 * ...
	 * @author ngs
	 */
	public class FeedbackPDF
	{
		private static var _pdf:PDF;
		private static var _page_x:Number;
		private static var _page_y:Number;
		private static var _curr_page_height:Number;
		private static var _img_correct:Sprite = new Sprite();
		private static var _img_wrong:Sprite = new Sprite();
		private static var _summary_page_y :Number;
		private static var _fmt:TextFormat = new TextFormat("Arial");
		private static var _tf:TextField = new TextField();
		private static var _save_pdf_xml:XMLList = Main.framework_xml.page.(@id == "completion").save_pdf;
		private static var _write_pdf:Boolean = _save_pdf_xml.hasComplexContent();
		
		public function FeedbackPDF() 
		{
			if (_write_pdf)
			{
				trace("save_pdf present");
				_img_correct.addChild(Images.tick);
				_img_correct.addChild(getImage(_save_pdf_xml.correct));
				_img_wrong.addChild(Images.cross);
				_img_wrong.addChild(getImage(_save_pdf_xml.wrong));
			}
		}
		
		private function getImage(image_file_name:String):Loader
		{
			var loader:Loader = new Loader();
			loader.load(new URLRequest(Main.content_path + image_file_name));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, itemLoaded);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loaderError);
			return loader;
		}
		
		private function itemLoaded(e:Event):void 
		{
			trace(this, "itemLoaded():", e.currentTarget.url)
			e.target.removeEventListener(Event.COMPLETE, itemLoaded);
			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loaderError);
			e.target.loader.parent.removeChildAt(0);
		}
		
		private function loaderError(e:IOErrorEvent):void
		{
			trace(this, "loaderError():", e.text);
			e.target.removeEventListener(Event.COMPLETE, itemLoaded);
			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loaderError);
			e.target.loader.parent.removeChildAt(1);
		}
		
		public static function resetPDF():void
		{
			if (_write_pdf)
			{
				trace("FeedbackPDF.resetPDF()")
				_pdf = new PDF(Orientation.PORTRAIT, Unit.POINT, Size.A4);
				_pdf.setDisplayMode(Display.REAL);
				_pdf.setBottomMargin(0);
			}
		}
		
		public static function addTitleImage():void
		{
			if (_write_pdf)
			{
				trace("FeedbackPDF.addTitleImage()")
				var margin:uint = 10;
				var header:uint = 100;
				
				var stage_bmp:BitmapData = new BitmapData(Main.stage_width, Main.stage_height, false, 0xffffff);
				stage_bmp.draw(Main.stg);
				
				var pg:Page = _pdf.addPage();
				var s:Number = (pg.width - margin * 2) / Main.stage_width;
				var matrix:Matrix = new Matrix();
				
				_curr_page_height = pg.height;
				
				matrix.scale(s, s);
				
				var scaled_bmp:BitmapData = new BitmapData(Main.stage_width * s, Main.stage_height * s, false, 0xffffff);
				scaled_bmp.draw(stage_bmp, matrix, null, null, null, true);
				
				_pdf.addImage(new Bitmap(scaled_bmp), margin, header);
				
				_summary_page_y  = header + scaled_bmp.height + 10;
				
				//_pdf.setXY(0, _summary_page_y );
				//_pdf.setFont( FontFamily.ARIAL, Style.NORMAL, 24 );
				//_pdf.textStyle ( new RGBColor ( 0x000000 ) );
				//_pdf.addMultiCell(pg.width, 30, _save_pdf_xml.save_pdf.title, 0, "C");
				_fmt.align = "center";
				_fmt.size = 24;
				_fmt.bold = false;
				_tf.defaultTextFormat = _fmt;
				_tf.wordWrap = false;
				_tf.height = 30;
				_tf.width = pg.width
				_tf.text = _save_pdf_xml.title;
				_pdf.addImage(_tf, 0, _summary_page_y, 0, 0, ImageFormat.PNG);
				
				_summary_page_y += 40;
				
				_pdf.addPage();
				_page_y = 10;
			}
		}
		
		public static function addResultImage(current_question:uint, num_questions:uint, current_level:uint, num_levels:uint,result:Boolean):void
		{
			if (_write_pdf)
			{
				var stage_bmp:BitmapData = new BitmapData(Main.stage_width, Main.stage_height, false, 0xffffff);
				stage_bmp.draw(Main.stg);
				
				var pg:Page = _pdf.getCurrentPage();
				var s:Number = pg.width / (Main.stage_width * 4);
				var matrix:Matrix = new Matrix();
				
				var w:Number = Main.stage_width * s;
				var h:Number = Main.stage_height * s;
				
				if (_page_y + h > _curr_page_height)
				{
					_pdf.addPage();
					_page_y = 10;
				}
				
				_page_x = 10;
				
				// Number
				_pdf.setFont( FontFamily.ARIAL, Style.NORMAL, 14 );
				_pdf.textStyle ( new RGBColor ( 0x000000 ) );
				_pdf.addText(String(current_question), _page_x, _page_y + 20);
				
				_page_x += 20;
				
				// Thumbnail
				matrix.scale(s, s);
				var scaled_bmp:BitmapData = new BitmapData(w, h, false, 0xffffff);
				scaled_bmp.draw(stage_bmp, matrix, null, null, null, true);
				_pdf.addImage(new Bitmap(scaled_bmp), _page_x, _page_y);
				
				// tick or cross
				var img:Sprite = result? _img_correct : _img_wrong;
				var img_x:Number = Main.stage_width - img.width;
				var img_y:Number = _page_y + (h - img.height) / 2;
				_pdf.addImage(img, img_x, img_y, 0, 0,ImageFormat.PNG);
				
				_page_x += w + 10;
				
				// Q text (if any)
				//_pdf.setXY(_page_x, _page_y);
				//_pdf.setFont( FontFamily.ARIAL, Style.NORMAL, 18 );
				//_pdf.textStyle ( new RGBColor ( 0x000000 ) );
				//var txt:String = Gameplay.question_xml.display.(@id == "question").text;
				//_pdf.addMultiCell(img_x - _page_x, 20, txt, 0, "L");// Encoding.encodeString(txt), 0, "L");
				
				_fmt.align = "left";
				_fmt.size = 18;
				_fmt.bold = false;
				_tf.defaultTextFormat = _fmt;
				_tf.wordWrap = true;
				_tf.height = 100;
				_tf.width = img_x - _page_x;
				_tf.text = Gameplay.question_xml.display.(@id == "question").text;
				_pdf.addImage(_tf, _page_x, _page_y, 0, 0, ImageFormat.PNG);
				
				_page_y += h + 10;
				
			}
		}
		
		public static function printPDF(e:Event):void
		{
			if (_write_pdf)
			{
				var player_name:String = Feedback.input_box.text;
				var date:Date = new Date();
				
				_pdf.gotoPage(1);
				var pg:Page = _pdf.getCurrentPage();
				
				_pdf.setXY(0, 0);
				
				_tf = new TextField();
				
				//_pdf.setFont( FontFamily.ARIAL, Style.NORMAL, 14 );
				//_pdf.addMultiCell(pg.width - 10, 30, date.toLocaleString(), 0, "R");
				_fmt.align = "right";
				_fmt.size = 14;
				_fmt.bold = false;
				_tf.defaultTextFormat = _fmt;
				_tf.wordWrap = false;
				_tf.height = 30;
				_tf.width = pg.width - 10;
				_tf.text = date.toLocaleString();
				_pdf.addImage(_tf, 0, 10, 0, 0, ImageFormat.PNG);
				
				//_pdf.setFont( FontFamily.ARIAL, Style.BOLD, 36 );
				//_pdf.addMultiCell(pg.width, 60, player_name, 0, "C");
				_fmt.align = "center";
				_fmt.size = 36;
				_fmt.bold = true;
				_tf.defaultTextFormat = _fmt;
				_tf.wordWrap = false;
				_tf.height = 40;
				_tf.width = pg.width;
				_tf.text = player_name;
				_pdf.addImage(_tf, 0, 40, 0, 0, ImageFormat.PNG);
				
				var total:uint = 0;
				var correct:uint = 0;
				
				var level_breakdown_string:String = "";
				
				for (var k:uint = 0; k < GameState.player_responses.length; k++)
				{
					for (var j:uint = 0 ; j < GameState.player_responses[k].length; j++)
					{
						total += 1;
						correct += (GameState.player_responses[k][j].correct)? 1 : 0 ;
					}
					level_breakdown_string += String(correct) + "/" + String(total) + (k < GameState.player_responses.length-1? "  ":"");
					total = 0;
					correct = 0;
				}
				
				trace( "level_breakdown_string : " + level_breakdown_string );
				
				_pdf.setXY(0, _summary_page_y+20);
				
				_pdf.setFont( FontFamily.ARIAL, Style.BOLD, 120 );
				_pdf.addMultiCell(pg.width, 100, GameState.percent_score + "%", 0, "C");
				
				_pdf.setXY(0, _summary_page_y + 140);
				_pdf.setFont( FontFamily.ARIAL, Style.BOLD, 36 );
				_pdf.addMultiCell(pg.width, 36, level_breakdown_string, 0, "C");
				
				var file_name:String = player_name;
				file_name += "_" + date.fullYear + twoChar(date.month + 1) + twoChar(date.date) + "-" + twoChar(date.hours) + twoChar(date.minutes);
				file_name += "_" + Main.framework_xml.page.(@id == "introduction").title;
				
				savePDF(file_name);
			}
		}
		
		static private function twoChar(n:Number):String
		{
			var s:String = String(int(n));
			return (s.length == 1)? "0" + s:s;
		}
		
		private static function savePDF(file_name:String):void
		{
			var bytes:ByteArray = _pdf.save(Method.LOCAL);
			//file_name = "test";
			var fileRef:FileReference = new FileReference();
			fileRef.save(bytes, file_name + ".pdf");
			//fileRef.save(this.save(Method.LOCAL), "test.pdf");
		}
		
	}
	
}