using System;
using System.Collections.Generic;
using System.Text;
using MySQL.Grt;
using MySQL.Utilities;
using MySQL.GUI.Workbench;

namespace MySQL.GUI.Workbench.Plugins
{
  class PrintPreviewDialog : Plugin
  {
    System.Drawing.Printing.PrintDocument printDocument;
    GrtValue grtArguments;
    int pageNumber;
    int pageCount;


    public PrintPreviewDialog(GrtManager GrtManager, GrtValue GrtList)
      : base(GrtManager, GrtList)
		{
      grtArguments = GrtList;
    }

    public override void Execute()
    {
      printDocument = new System.Drawing.Printing.PrintDocument();

      printDocument.OriginAtMargins = true;
      printDocument.BeginPrint += new System.Drawing.Printing.PrintEventHandler(printDocument_BeginPrint);
      printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDocument_PrintPage);
      printDocument.DefaultPageSettings.Landscape = MySQL.GUI.Workbench.Plugins.Printing.isLandscape(grtArguments);

      System.Windows.Forms.PrintPreviewDialog preview = new System.Windows.Forms.PrintPreviewDialog();

      preview.Document = printDocument;
      preview.UseAntiAlias = true;

      preview.ShowDialog();
    }

    void printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    {
      pageNumber = 0;
      pageCount = -1;      
    }

    void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
      MySQL.GUI.Workbench.Plugins.Printing prn= new MySQL.GUI.Workbench.Plugins.Printing();

      if (pageCount < 0)
        pageCount = prn.getPageCount(grtArguments);

      e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Red), 0, 0,
        e.PageSettings.PaperSize.Width - 1, e.PageSettings.PaperSize.Height - 1);

      e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Green), e.PageBounds);

      IntPtr hdc = e.Graphics.GetHdc();

      if (prn.printPageHDC(grtArguments, pageNumber++, hdc,
        e.PageSettings.PaperSize.Width, e.PageSettings.PaperSize.Height) < 1)
        e.HasMorePages = false;
      else
        e.HasMorePages = pageNumber < pageCount;
      e.Graphics.ReleaseHdc();
    }

  }
}
