using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using Rg.Plugins.Popup.Animations;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;

namespace InABox.Mobile
{
    public class MobileDocument
    {
        public string FileName { get; set; }
        public byte[] Data { get; set; }

        public MobileDocument()
        {
            FileName = "";
            Data = new byte[] { };
        }
        
        public MobileDocument(string filename, byte[] data)
        {
            FileName = filename;
            Data = data;
        }
        
        public void ConvertToPDF()
        {
            using (var img = new MemoryStream(Data))
            {
                var image = new PdfBitmap(img);

                var pdfDoc = new PdfDocument();

                var section = pdfDoc.Sections.Add();
                section.PageSettings.Margins.All = 0;
                section.PageSettings.Width = image.Width;
                section.PageSettings.Height = image.Height;

                var page = section.Pages.Add();
                page.Graphics.DrawImage(image, 0, 0, page.Size.Width, page.Size.Height);

                using (var ms = new MemoryStream())
                {
                    pdfDoc.Save(ms);
                    Data = ms.GetBuffer();
                    FileName = Path.ChangeExtension(FileName, "pdf");                
                }
            }

        }
        
        public bool IsPDF() => FileName.ToUpper().EndsWith(".PDF");

        
        public static async Task<MobileDocument> From<TSource, TOptions>(TSource source) 
            where TSource : MobileDocumentSource
            where TOptions : MobileDocumentOptions<TSource>
        {
            var result = await source.From();
            return result;
        }
        
        public static async Task<MobileDocument> From<T>(MobileDocumentOptions<T> options) where T : MobileDocumentSource
        {
            var source = (T)Activator.CreateInstance(typeof(T), new object[] { options });
            var result = await source.From();
            return result;
        }
        
    }
}