// Printing.cs created with MonoDevelop
// User: klose at 23:56 09.03.2009
// CVS release: $Id: Printer.cs,v 1.17 2011-04-19 12:36:58 klose Exp $
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2009  Thomas Klose, Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Threading;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using Gtk;

using Hiperscan.GUI.Figure;
using Hiperscan.Unix;


namespace Hiperscan.GUI
{

	public class Printer : Gtk.PrintOperation
	{
		IPlotEngine plot = null;
		Gdk.Pixbuf pixbuf = null;

		public Printer(Window parent, IPlotEngine plot)
		{
			this.plot = plot;
			
			PrintSettings settings = new PrintSettings();
			this.PrintSettings = settings;

			try
			{
				Console.WriteLine("call Gtk.PrintOperation.Run() ...");
				
//				if (System.Environment.OSVersion.Version.Major > 5)
//					this.Run(PrintOperationAction.Print, parent);
//				else
					this.Run(PrintOperationAction.PrintDialog, parent);
			}
			catch (Exception ex)
			{
				new InfoMessage(parent, 
				                Catalog.GetString("A problem occured while printing:") +
				                " " + ex.Message);
			}
		}
		
		private Gdk.Pixbuf CreatePixbuf(IPlotEngine plot, int width, int height, float xdpi, float ydpi)
		{
//			bool sav_legend_visible = plot.LegendVisible;
			
			try
			{
				using (Bitmap bmp = new Bitmap(width, height))
				{

					if (MainClass.OS == MainClass.OSType.Windows)
					{
						bmp.SetResolution(xdpi, ydpi);
						using (Graphics g = Graphics.FromImage(bmp))
						{
							g.PageUnit = GraphicsUnit.Point;
							g.Clear(Color.White);
							plot.Draw(g, new Rectangle(0, 0, 
							                           (int)Math.Round(width* 72f/xdpi),
							                           (int)Math.Round(height*72f/ydpi)
							                           )
							          );
							plot.DrawOverlays(g, false);
							if (plot.LegendVisible)
								plot.DrawLegend(g);
						}
					}
					else
					{
						// rendering in higher resolutions does not work with Linux :(
						using (Graphics g = Graphics.FromImage(bmp))
						{
							g.Clear(Color.White);
							plot.Draw(g, new Rectangle(0, 0, bmp.Width-1, bmp.Height-1));
							plot.DrawOverlays(g, false);
							if (plot.LegendVisible)
								plot.DrawLegend(g);
						}
					}
				
					using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
					{
						bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
						
						return new Gdk.Pixbuf(stream.ToArray());
					}
				}
			}
			finally
			{
//				plot.LegendVisible = sav_legend_visible;
				plot.Refresh(false);
			}
		}
		
		protected override void OnRequestPageSetup(Gtk.PrintContext context, int page_nr, Gtk.PageSetup setup)
		{
			Console.WriteLine("OnRequestPageSetup() called");
		}
		
		protected override bool OnPaginate(Gtk.PrintContext context)
		{
			Console.WriteLine("OnPaginate() called");
			
			return true;
		}
		
		protected override void OnBeginPrint(Gtk.PrintContext context)
		{
			Console.WriteLine("OnBeginPrint() called");
			base.OnBeginPrint(context);
			
			this.NPages = 1;
		}

		protected override void OnDrawPage(Gtk.PrintContext context, int page_no)
		{
			Console.WriteLine("OnDrawPage() called");
			base.OnDrawPage(context, page_no);

			double k = this.PrintSettings.Scale / 100f;
			Console.WriteLine("Printing with scaling factor " + k);

			int w = (int)Math.Round(k*context.Width);
			//int h = (int)Math.Round(k*context.Height);
			int h = (int)Math.Round(w/1.618f);

			Console.WriteLine("Rendering image to print ({0}x{1})...", w, h);
			try
			{
				this.pixbuf = this.CreatePixbuf(this.plot, w, h, (float)context.DpiX, (float)context.DpiY);
			}
			catch (Exception ex)
			{
				this.pixbuf = new Gdk.Pixbuf(MainClass.Assembly, "GUI.Icons.printer-error.png");
				Console.WriteLine("Error while calling CreatePixbuf(): " + ex.ToString());
			}

			using (Cairo.Context cr = context.CairoContext)
			{
				Gdk.CairoHelper.SetSourcePixbuf(cr, this.pixbuf, 0f, 0f);
				context.CairoContext.Paint();
			}
		}

		protected override void OnEndPrint(Gtk.PrintContext context)
		{
			Console.WriteLine("OnEndPrint() called");
			base.OnEndPrint(context);

			if (this.pixbuf != null)
				this.pixbuf.Dispose();
			
			((IDisposable)context.CairoContext.GetTarget()).Dispose();
			((IDisposable)context.CairoContext).Dispose();
			context.Dispose();
		}		
	}
}
