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

namespace MySQL.GUI.Workbench.Plugins
{
  public class PrintDialog : Plugin
  {
    System.Windows.Forms.PrintDialog printDialog;
    System.Drawing.Printing.PrintDocument printDocument;
    GrtValue grtArguments;
    int pageNumber;
    int pageCount;


    public PrintDialog(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);

      printDialog = new System.Windows.Forms.PrintDialog();
      printDialog.Document = printDocument;
      printDialog.AllowPrintToFile = true;

      pageNumber = 0;
      pageCount = -1;

      if (printDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
      {
        printDocument.Print();
      }
    }

    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);

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

  }
}
