using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;

namespace FaxPrint
{
    internal class MultiPagePrint
    {
        private Font printFont;
        private string documentText;

        public MultiPagePrint()
        {
            this.printFont = new Font("Arial", 11f, FontStyle.Regular, GraphicsUnit.Point);
        }

        public void Print(string fileName, bool useFaxController)
        {
            this.documentText = File.ReadAllText(fileName);

            var printDocument = new PrintDocument();
            if (useFaxController)
            {
                var controller = new FaxPrintController();
                printDocument.PrintController = new PrintControllerWithStatusDialog(controller);
            }
            // printDocument.OriginAtMargins = true;
            printDocument.DocumentName = Path.GetFileNameWithoutExtension(fileName);
            printDocument.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);
            printDocument.Print();
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            // aus http://msdn.microsoft.com/en-us/library/cwbe712d.aspx
            int charactersOnPage = 0;
            int linesPerPage = 0;

            e.Graphics.MeasureString(documentText, this.printFont, e.MarginBounds.Size, StringFormat.GenericTypographic,
                out charactersOnPage, out linesPerPage);
            e.Graphics.DrawString(documentText, this.printFont, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic);
            documentText = documentText.Substring(charactersOnPage);

            e.HasMorePages = (documentText.Length != 0);
        }
    }
}
