using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using HiQPdf;
using Interfaces;

namespace PDFExporter
{
    public class PdfExporter:IFileExporter
    {
        //private Stream str = new MemoryStream();
        public void Export(string fileContent, string baseUrl, out Stream exportStream)
        {
            //Stream pdfExportStream = new MemoryStream();
            //var t = new Thread(new ParameterizedThreadStart(DoExport));//()=>DoExport(fileContent, baseUrl));
            //var t2 = Task.Factory.StartNew(() => DoExport(fileContent, baseUrl));

            //t.SetApartmentState(ApartmentState.STA);
            //t.Start();
            //t.Join();

            //exportStream = t2.Result;
            //FileStream fileStream = File.Create("pdfexportertst.pdf", (int)t2.Result.Length);
            //// Initialize the bytes array with the stream length and then fill it with data
            //byte[] bytesInStream = new byte[t2.Result.Length];
            //t2.Result.Read(bytesInStream, 0, bytesInStream.Length);
            //// Use write method to write to the file specified above
            //fileStream.Write(bytesInStream, 0, bytesInStream.Length);
            //fileStream.Flush(true);
            //fileStream.Close();
            ////CopyStream(t2.Result, fs);
            //Debug.WriteLine(t2.Result.Length);

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();
            converter.MediaType = "print";
            converter.RunJavaScript = true;
            converter.WaitBeforeConvert = 1;

            converter.Document.FitPageWidth = true;
            converter.Document.ForceFitPageWidth = true;
            converter.BrowserZoom = 135;
            converter.Document.Properties.CreationDate = DateTime.UtcNow;
            // set converter options
            converter.Document.PageSize = PdfPageSize.A4;
            converter.Document.PageOrientation = PdfPageOrientation.Portrait;
            //converter.Options.WebPageWidth = webPageWidth;
            //converter.Options.WebPageHeight = webPageHeight;

            // create a new pdf document converting an url
            exportStream = new MemoryStream();
            converter.ConvertHtmlToStream(fileContent, baseUrl, exportStream);

            // save pdf document
            //doc.Save(Response, false, "Sample.pdf");

            // close pdf document
            //doc.Close();

        }

        private void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[16 * 1024];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

        public ExportProviderDetails GetDetails()
        {
            return new ExportProviderDetails
            {
                Type = "PDF"
            };
        }
        
        //Stream DoExport(string fileContent, string baseUrl)
        //{
        //    #region MyRegion
        //    //var pdfExporter = new HtmlToPdfConverter();
        //    //var settings2 = new IEConverterSettings();
        //    //settings2.AdditionalDelay = 2000;
        //    //pdfExporter.ConverterSettings = settings2;
        //    //PdfDocument doc = pdfExporter.Convert(fileContent, baseUrl);


        //    //var conv = new HtmlToPdfConverter();

        //    //PdfDocument document = new PdfDocument();
        //    ////Set page margins and dimensions.

        //    //PdfUnitConvertor convertor = new PdfUnitConvertor();

        //    //float width = convertor.ConvertToPixels(document.PageSettings.Width, PdfGraphicsUnit.Point);
        //    //float height = convertor.ConvertToPixels(document.PageSettings.Height, PdfGraphicsUnit.Point);

        //    //var settings = new IEConverterSettings();

        //    //settings.EnableHyperLink = true;
        //    //settings.EnableJavaScript = true;
        //    //settings.SplitImages = false;
        //    //settings.SplitTextLines = false;

        //    //settings.Margin.All = 20.0f;

        //    //settings.PdfPageSize = PdfPageSize.A4;

        //    //conv.ConverterSettings = settings;

        //    ////Convert the URL/HTML string by providing the required width and          height.
        //    //var doc = conv.Convert(@"http://www.bbc.co.uk", width, height, AspectRatio.KeepWidth);
        //    //doc.PageSettings.Size = PdfPageSize.A4;
        //    //doc.PageSettings.SetMargins((float)20.0f);

        //    //doc.Save("c:\\zzz\\test3.pdf");
        //    ////doc.Close(true);


        //    #endregion
        //    // instantiate a html to pdf converter object
        //    HtmlToPdf converter = new HtmlToPdf();

        //    // set converter options
        //    converter.Options.PdfPageSize = PdfPageSize.A4;
        //    converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
        //    converter.Options.CssMediaType = HtmlToPdfCssMediaType.Print;
        //    //converter.Options.WebPageWidth = webPageWidth;
        //    //converter.Options.WebPageHeight = webPageHeight;

        //    // create a new pdf document converting an url
        //    PdfDocument doc = converter.ConvertHtmlString(fileContent, baseUrl);
        //    doc.Margins = new PdfMargins(20.0f, 20.0f,20.0f,20.0f);
        //    // save pdf document
        //    //doc.Save(Response, false, "Sample.pdf");
            
        //    // close pdf document
        //    //doc.Close();
        //    File.Delete("plugintest.pdf");
        //    //doc.Save("plugintest.pdf");
        //    MemoryStream ms = new MemoryStream();
        //    doc.Save(ms);
        //    //doc.Save(exportStream);
        //    //FileStream fs = new FileStream("pdfexporterfs2.pdf", FileMode.Create);
        //    //CopyStream(ms, fs);
        //    //fs.Flush(true);
        //    //fs.Close();
        //    //fs.Dispose();
        //    //doc.Save(fs);
        //    //ms.WriteTo(fs);
        //    //fs.Flush(true);
        //    //fs.Close();
        //    //fs.Dispose();

        //    doc.Close();
        //    return ms;
        //    //ms.CopyTo(str);
        //    //ms.Flush();
        //    //ms.Close();
        //    //ms.Dispose();
        //}
    }
}
