using System.Drawing;
using Tesseract;

namespace ZionGraphics.Filtering
{
    class AutoRotate : IFilter
    {
        public override Bitmap Apply(Bitmap original)
        {
            AutoRotate.FixImageOrientation(original);
            return original;
        }

        private static RotateFlipType GetRotateFlipType(double angle)
        {
            if (90.0.Equals(angle))
            {
                return RotateFlipType.Rotate90FlipNone;
            }
            if (180.0.Equals(angle))
            {
                return RotateFlipType.Rotate180FlipNone;
            }
            if (!270.0.Equals(angle))
            {
                return RotateFlipType.RotateNoneFlipNone;
            }
            return RotateFlipType.Rotate270FlipNone;
        }

        public static void FixImageOrientation(Bitmap image)
        {
            using (TesseractEngine tesseractEngine = new TesseractEngine("./tessdata", "por+por2+por3+osd", EngineMode.Default))
            {
                using (Page page = tesseractEngine.Process(image, new PageSegMode?(PageSegMode.OsdOnly)))
                {
                    int num = 0;
                    float num2 = 0f;
                    try
                    {
                        page.DetectBestOrientation(out num, out num2);
                        if (num != 0 && num2 > 1.0)
                        {
                            image.RotateFlip(AutoRotate.GetRotateFlipType((double)num));
                        }
                    }
                    catch
                    {

                    }

                }
            }
        }
    }
}
