using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;

namespace NistUtilities
{
    public class EmnistAdapter : NistAdapter
    {
        public EmnistAdapter(Bitmap sourceBitmap) : base(sourceBitmap)
        {
        }

        public override Bitmap To28X28()
        {
            const int padding = 2;
            const int blurRadial = 1;
            using (var roiBitmap = FindRegionOfInterest())
            using (var paddedBitmap = PadAndSquareBitmap(roiBitmap, padding))
            using (var blurredBitmap = new GaussianBlur(paddedBitmap).Process(blurRadial))
            {
                var targetImage = new Bitmap(28, 28);
                blurredBitmap.SetResolution(roiBitmap.HorizontalResolution, roiBitmap.VerticalResolution);
                targetImage.SetResolution(roiBitmap.HorizontalResolution, roiBitmap.VerticalResolution);
                using (var targetGraphics = Graphics.FromImage(targetImage))
                {
                    targetGraphics.InterpolationMode = InterpolationMode.High;
                    targetGraphics.CompositingQuality = CompositingQuality.HighQuality;
                    targetGraphics.SmoothingMode = SmoothingMode.AntiAlias;

                    targetGraphics.FillRectangle(new SolidBrush(Color.White),
                        new Rectangle(0, 0, targetImage.Width, targetImage.Height));

                    var destRect = new RectangleF(0, 0, targetImage.Width, targetImage.Height);
                    targetGraphics.DrawImage(blurredBitmap, destRect);
                }

                return targetImage;
            }
        }

        
        
        
        
        
        
        
        
        
        
        

        private static Bitmap PadAndSquareBitmap(Image bitmap, int padding)
        {
            var size = Math.Max(bitmap.Width, bitmap.Height) + 2 * padding;
            var ret = new Bitmap(size, size, bitmap.PixelFormat);

            var origin = new Point(
                ret.Width / 2 - bitmap.Width / 2,
                ret.Height / 2 - bitmap.Height / 2);
            var destRect = new Rectangle(origin, bitmap.Size);
            var srcRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            using (var graphics = Graphics.FromImage(ret))
            {
                graphics.FillRectangle(new SolidBrush(Color.White), 0, 0, ret.Width, ret.Height);
                graphics.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);
            }
            return ret;
        }
    }
}

