using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Drawing;
using C1.C1Pdf;

namespace PdfExport.Web
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class PdfConverter : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            using (var sr = new StreamReader(context.Request.InputStream))
            {
                // read html
                var html = sr.ReadToEnd();

                // create pdf document
                var pdf = new C1PdfDocument();
                var font = new Font("Tahoma", 12);
                var brush = Brushes.Black;
                var rc = pdf.PageRectangle;
                rc.Inflate(-72, -72);

                // prepare to render footer
                var footerFont = new Font("Times New Roman", 8, FontStyle.Italic);
                var footerBrush = Brushes.DarkGray;
                var rcFooter = rc;
                rcFooter.Y = rc.Bottom + 30;
                rcFooter.Height = 30;

                // render html into document
                for (int offset = 0; ; )
                {
                    // draw this page
                    offset = pdf.DrawStringHtml(html, font, brush, rc, offset);

                    // draw footer
                    var footer = string.Format("C1Pdf from Silverlight - Page {0}", pdf.Pages.Count);
                    pdf.DrawString(footer, footerFont, footerBrush, rcFooter);
                    pdf.DrawLine(Pens.DarkGray, rcFooter.X, rcFooter.Y, rcFooter.Right, rcFooter.Y);

                    // stop when done
                    if (offset == int.MaxValue)
                    {
                        break;
                    }

                    // next page
                    pdf.NewPage();
                }

                // save to output file
                var fn = Path.GetRandomFileName();
                fn = Path.ChangeExtension(fn, ".pdf");
                fn = Path.Combine("Output", fn);
                var path = Path.Combine(context.Request.PhysicalApplicationPath, fn);
                pdf.Save(path);

                // return output file name
                context.Response.ContentType = "text/plain";
                context.Response.Write(fn);

                // delete old output files
                CleanUpOldFiles(Path.GetDirectoryName(path));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        void CleanUpOldFiles(string path)
        {
            var now = DateTime.Now;
            foreach (string fn in Directory.GetFiles(path, "*.pdf"))
            {
                if (now.Subtract(File.GetLastAccessTime(fn)).TotalMinutes > 1)
                {
                    File.Delete(fn);
                }
            }
        }
    }
}
