using SanShared;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocToPDFConverter;
using Syncfusion.Pdf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BerichtGen
{
    class Bericht
    {
        private List<Image> _listImages;
        /// <summary>
        /// Erstellt
        /// </summary>
        /// <param name="source">Die zuverwendete Vorlagenname</param>
        /// <param name="savepath">Pfad zum Speichern</param>
        /// <param name="filename"></param>
        /// <param name="daten"></param>
        /// <param name="bilderObjects">Zur zeit ohne Implementierung</param>
        /// <param name="tableContents">Für Tabellen anzeige</param>
        /// <param name="erzeugeDOC">Ein doc datei soll erzeugt werden</param>
        /// <param name="erzeugePDF">Ein Pdf datei soll erzeugt werden</param>
        public void Erzeuge(string source, string savepath,string filename, Hashtable daten,List<BilderObject> bilderObjects,DataTable tableContents, bool erzeugeDOC = false , bool erzeugePDF = true)
        {
            if (bilderObjects != null)
            {
                _listImages = new List<Image>();
                foreach (BilderObject current in bilderObjects)
                {
                    Image image = Image.FromFile(current.Path);
                    _listImages.Add(ResizeImage(image, CalculateImageSizeForDocument(image.Height, image.Width)));
                    image.Dispose();
                }
            }

            WordDocument wordDocument = new WordDocument(source);
            
            string[] fieldnames = null;
            string[] fieldvalues = null;

            if(fieldnames == null || fieldvalues == null)
            {
                fieldnames = new string[daten.Count];
                fieldvalues = new string[daten.Count];
            }

            uint counter = 0;
            foreach(DictionaryEntry hashtable in daten)
            {
                fieldnames[counter] = hashtable.Key.ToString();
                if (hashtable.Value == null)
                {
                    fieldvalues[counter] = "";
                }
                else
                {
                    fieldvalues[counter] = hashtable.Value.ToString();
                }
                counter++;
                
            }
            
            

            wordDocument.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

            

            if (tableContents != null)
                wordDocument.MailMerge.ExecuteGroup(tableContents);

            wordDocument.MailMerge.Execute(fieldnames, fieldvalues);

            if(erzeugeDOC)
                wordDocument.Save(Path.Combine(savepath,string.Format("{0}.doc",filename)), Syncfusion.DocIO.FormatType.Doc);

            if (erzeugePDF)
            {
                string speichername = Path.Combine(savepath, string.Format("{0}.pdf", filename));
                DocToPDFConverter docToPDFConverter = new DocToPDFConverter();
                PdfDocument pdf = docToPDFConverter.ConvertToPDF(wordDocument);
                try
                {
                    pdf.Save(speichername);

                }
                catch
                {

                }
                finally
                {
                    //pdf.Dispose();
                }
            }
           
        }
        private readonly double _cmPixel = 0.393700787;
        private readonly int _dpi = 120;
        private readonly double _imgWidthCmMax = 8.0;

        private Size CalculateImageSizeForDocument(int height, int width)
        {
            double num = (double)height / (double)width;
            double num2 = this._imgWidthCmMax * num;
            int h = (int)(num2 * _cmPixel * (double)_dpi);
            int w = (int)(_imgWidthCmMax * _cmPixel * (double)_dpi);
            return new Size(w, h);
        }

        private Image ResizeImage(Image image, Size size)
        {
            int width = image.Width;
            int height = image.Height;
            float num = (float)size.Width / (float)width;
            float num2 = (float)size.Height / (float)height;
            float num3 = (num2 < num) ? num2 : num;
            int width2 = (int)((float)width * num3);
            int height2 = (int)((float)height * num3);
            Bitmap bitmap = new Bitmap(width2, height2);
            try
            {
                bitmap.SetResolution(120f, 120f);
                Graphics graphics = Graphics.FromImage(bitmap);
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                graphics.DrawImage(image, 0, 0, width2, height2);
                graphics.Dispose();

            }
            catch(Exception)
            {

            }
            finally
            {
                System.GC.Collect();
            }
            return bitmap;
        }

        private void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs args)
        {
            if(args.FieldName == "UVImage")
            {
                string source  = args.FieldValue.ToString();
                if (!File.Exists(source)) return;
                args.Image = Image.FromFile(source);
            }
        }



    }
}
