using OpenCvSharp;
using System;
using System.Collections.Generic;

namespace OpenCV.OpenCV
{
    partial class OpenCVClass : IDisposable
    {
        IplImage _cvt;
        IplImage _gray;
        IplImage _bin;

        IplConvKernel _convKernel;

        public IplImage InterimGrayImage { get; set; }
        public IplImage InterimBinaryImage { get; set; }

        public IplImage GrayScale(IplImage src)
        {
            _gray = new IplImage(src.Size, BitDepth.U8, 1);
            Cv.CvtColor(src, _gray, ColorConversion.BgrToGray);
            InterimGrayImage = new IplImage(_gray.Size, BitDepth.U8, 1);
            Cv.Copy(_gray, InterimGrayImage);
            return _gray;
        }

        public IplImage InversionImage(IplImage src)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            Cv.Not(src, _cvt);
            return _cvt;
        }

        public IplImage Binary(IplImage src, int threshold)
        {
            _bin = GrayScale(src);
            Cv.Threshold(_bin, _bin, threshold, 255, ThresholdType.Binary);
            InterimBinaryImage = new IplImage(_bin.Size, BitDepth.U8, 1);
            Cv.Copy(_bin, InterimBinaryImage);
            return _bin;
        }

        public IplImage Blur(IplImage src)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            Cv.Smooth(src, _cvt, SmoothType.Blur, 9); // param1은 홀수, 중간 픽셀 선택을 위함
            return _cvt;
        }

        public IplImage ZoomIn(IplImage src)
        {
            _cvt = new IplImage(new CvSize(src.Width * 2, src.Height * 2) , BitDepth.U8, 3);
            Cv.PyrUp(src, _cvt, CvFilter.Gaussian5x5);
            return _cvt;
        }

        public IplImage ZoomOut(IplImage src)
        {
            _cvt = new IplImage(new CvSize(src.Width / 2, src.Height / 2), BitDepth.U8, 3);
            Cv.PyrDown(src, _cvt, CvFilter.Gaussian5x5);
            return _cvt;
        }

        public IplImage Resize(IplImage src, double widthRate, double heightRate)
        {
            _cvt = new IplImage(new CvSize((int)(src.Width * widthRate), (int)(src.Height * heightRate)), BitDepth.U8, 3);
            Cv.Resize(src, _cvt, Interpolation.Linear);
            return _cvt;
        }

        public IplImage Slice(IplImage src, int x, int y, int roiWidht, int roiHeight)
        {
            //slice = new IplImage(new CvSize(roiWidht, roiHeight), BitDepth.U8, 3);

            //src.ROI = new CvRect(x, y, roiWidht, roiHeight);
            //src.SetROI(new CvRect(x, y, roiWidht, roiHeight));
            //Cv.SetImageROI(src, new CvRect(x, y, roiWidht, roiHeight));

            //Cv.Copy(src, slice);
            //Cv.Resize(src, slice);
            //slice = src.Clone(); // 속성까지 복사되어 채널 등 값이 변경됨

            //src.ResetROI();
            //Cv.ResetImageROI(src);

            CvRect roi = new CvRect(x, y, roiWidht, roiHeight);
            _cvt = src.Clone(roi);

            return _cvt;
        }

        public IplImage Symmetry(IplImage src, FlipMode mode)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            Cv.Flip(src, _cvt, mode);
            return _cvt;
        }

        public IplImage Rotate(IplImage src, double angle)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            CvMat matrix = Cv.GetRotationMatrix2D(new CvPoint2D32f(src.Width / 2, src.Height / 2), angle, 1);
            Cv.WarpAffine(src, _cvt, matrix, Interpolation.Linear, CvScalar.ScalarAll(0));
            return _cvt;
        }

        public IplImage AffineImage(IplImage src, CvPoint2D32f[] srcPoints, CvPoint2D32f[] dstPoints)
        {
            if (srcPoints.Length != 3 || dstPoints.Length != 3)
                return null;

            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            CvMat matrix = Cv.GetAffineTransform(srcPoints, dstPoints);
            Cv.WarpAffine(src, _cvt, matrix, Interpolation.Linear, CvScalar.RealScalar(0));
            return _cvt;
        }

        public IplImage PerspectiveImage(IplImage src, CvPoint2D32f[] srcPoints, CvPoint2D32f[] dstPoints)
        {
            if (srcPoints.Length != 4 || dstPoints.Length != 4)
                return null;

            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            CvMat matrix = Cv.GetPerspectiveTransform(srcPoints, dstPoints);
            Cv.WarpPerspective(src, _cvt, matrix, Interpolation.Linear, CvScalar.RealScalar(0));
            return _cvt;
        }

        public IplImage DrawImage()
        {
            _cvt = new IplImage(new CvSize(640, 480), BitDepth.U8, 3);
            Cv.DrawLine(_cvt, new CvPoint(100, 100), new CvPoint(500, 200), CvColor.Blue, 20);
            Cv.DrawCircle(_cvt, new CvPoint(200, 200), 50, CvColor.Red, -1);
            Cv.DrawRect(_cvt, new CvPoint(300, 150), new CvPoint(500, 300), CvColor.Green, 5);
            Cv.DrawEllipse(_cvt, new CvPoint(150, 400), new CvSize(100, 50), 0, 90, 360, CvColor.Green, -1);
            Cv.PutText(_cvt, "Open CV", new CvPoint(400, 400), new CvFont(FontFace.HersheyComplex, 1, 1), CvColor.White);

            return _cvt;
        }

        public IplImage HSV(IplImage src)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);

            IplImage h = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage s = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage v = new IplImage(src.Size, BitDepth.U8, 1);

            Cv.CvtColor(src, _cvt, ColorConversion.BgrToHsv);
            Cv.Split(_cvt, h, s, v, null);
            
            _cvt.SetZero();

            // Hue
            //Cv.InRangeS(h, 20, 30, h); // Yellow
            //Cv.Copy(src, hsv, h);

            // Hue - Red
            IplImage lowerRed = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage upperRed = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage red = new IplImage(src.Size, BitDepth.U8, 1);
            Cv.InRangeS(h, 0, 10, lowerRed);
            Cv.InRangeS(h, 170, 179, upperRed);
            Cv.AddWeighted(lowerRed, 1.0, upperRed, 1.0, 0.0, red);
            Cv.Copy(src, _cvt, red);

            // Saturation
            //Cv.InRangeS(s, 20, 30, s);
            //Cv.Copy(src, hsv, s);

            // Value
            //Cv.InRangeS(v, 20, 30, v);
            //Cv.Copy(src, hsv, v);

            return _cvt;
        }

        public IplImage HSVRed(IplImage src)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);

            IplImage lowerRed = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage upperRed = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage red = new IplImage(src.Size, BitDepth.U8, 1);

            Cv.CvtColor(src, _cvt, ColorConversion.BgrToHsv);

            Cv.InRangeS(_cvt, new CvScalar(0, 100, 100), new CvScalar(10, 255, 255), lowerRed);
            Cv.InRangeS(_cvt, new CvScalar(170, 100, 100), new CvScalar(179, 255, 255), upperRed);
            Cv.AddWeighted(lowerRed, 1.0, upperRed, 1.0, 0.0, red);

            _cvt.SetZero();
            Cv.Copy(src, _cvt, red);

            return _cvt;
        }

        private void Release(params IplImage[] images)
        {
            for (int i = 0; i < images.Length; i++)
            {
                if (images[i] != null)
                    Cv.ReleaseImage(images[i]);
            }
        }

        public IplImage DilateImage(IplImage src, int threshold, int iteration)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 1);
            _cvt = Binary(src, threshold);
            Cv.Dilate(_cvt, _cvt, _convKernel, iteration);

            return _cvt;
        }

        public IplImage ErodeImage(IplImage src, int threshold, int iteration)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 1);
            _cvt = Binary(src, threshold);
            Cv.Erode(_cvt, _cvt, _convKernel, iteration);

            return _cvt;
        }

        public IplImage DEImage(IplImage src, int threshold, int iteration)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 1);
            _cvt = Binary(src, threshold);
            Cv.Dilate(_cvt, _cvt, _convKernel, iteration);
            Cv.Erode(_cvt, _cvt, _convKernel, iteration);

            return _cvt;
        }

        public IplImage EDImage(IplImage src, int threshold, int iteration)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 1);
            _cvt = Binary(src, threshold);
            Cv.Erode(_cvt, _cvt, _convKernel, iteration);
            Cv.Dilate(_cvt, _cvt, _convKernel, iteration);

            return _cvt;
        }

        public IplImage MorphologyImage(IplImage src, MorphologyOperation option, int iteration)
        {
            if (_convKernel == null)
                return null;

            _cvt = new IplImage(src.Size, BitDepth.U8, 1);
            _cvt = Binary(src, 50);

            Cv.MorphologyEx(_cvt, _cvt, _cvt, _convKernel, option, iteration);
            return _cvt;
        }

        public virtual void Dispose()
        {
            Release(
                _cvt, 
                _gray, 
                _bin,
                InterimGrayImage,
                InterimGrayImage);
        }
        
        public IplConvKernel ConvKernel
        {
            get { return this._convKernel; }
            set { this._convKernel = value; }
        }
    }
}
