using AForge.Imaging;
using AForge.Imaging.Filters;
using System.Drawing;
using System.Drawing.Imaging;

namespace ZionGraphics.Filtering
{
    class Deskewing : IFilter
    {
        public override Bitmap Apply(Bitmap bitmap)
        {
            Rectangle rec = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData data = bitmap.LockBits(rec, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

            DocumentSkewChecker skewChecker = new DocumentSkewChecker();
            double angle = skewChecker.GetSkewAngle(data);
            bitmap.UnlockBits(data);

            RotateBilinear rotationFilter = new RotateBilinear(-angle);
            rotationFilter.FillColor = Color.White;

            Bitmap clone = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
            using (Graphics gr = Graphics.FromImage(clone))
            {
                gr.DrawImage(bitmap, new Rectangle(0, 0, clone.Width, clone.Height));
            }

            clone = rotationFilter.Apply(clone);

            using (Graphics gr = Graphics.FromImage(bitmap))
            {
                gr.DrawImage(clone, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
            }

            return bitmap;
        }
    }
}
