using DominationStudioCLI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ocv = Domination.Unmanaged.OpenCV;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Program start");
            ConsoleKey key = ConsoleKey.NoName;

            ocv.VideoCapture capture = new ocv.VideoCapture();

            ocv.Mat frame = new ocv.Mat();
            ocv.Mat hsv = new ocv.Mat();
            ocv.Mat threshold;

            ocv.UserInterface.namedWindow("frame", ocv.WindowProperties.WindowAutoSize);
            ocv.UserInterface.namedWindow("hsv", ocv.WindowProperties.WindowAutoSize);
            ocv.UserInterface.namedWindow("threshold", ocv.WindowProperties.WindowAutoSize);
            capture.open(0);

            int width = (int)capture.get(ocv.VideoCaptureProperties.FrameWidth);
            int height = (int)capture.get(ocv.VideoCaptureProperties.FrameHeight);

            ColorTrack ct = new ColorTrack();
            ct.Show();

            do
            {
                capture.read(frame);

                ocv.OperationsOnArrays.flip(frame, frame, 1);

                ocv.ImageFiltering.blur(frame, frame, new System.Drawing.Size(3, 3));

                ocv.MiscellaneousImageTransformation.cvtColor(frame, hsv, ocv.ColorConversion.BGR2HSV);

                threshold = new ocv.Mat(height, width, ocv.MatrixType.T8UC1);

                ocv.OperationsOnArrays.inRange(hsv, ct.GetMin(), ct.GetMax(), threshold);

                ocv.ImageFiltering.blur(threshold, threshold, new System.Drawing.Size(3, 3));

                float[,] circles;
                ocv.FeatureDetection.HoughCircles(threshold, out circles, 2, height / 4, 100, 40, 20, 200);

                for (int i = 0; i < circles.Length / 3; i++)
                {
                    ocv.DrawingFunctions.circle(frame, new System.Drawing.Point((int)circles[i, 0], (int)circles[i, 1]), (int)circles[i, 2], System.Drawing.Color.Red, 3, 0, 0);
                }

                ocv.UserInterface.imshow("frame", frame);
                ocv.UserInterface.imshow("hsv", hsv);
                ocv.UserInterface.imshow("threshold", threshold);

                key = (ConsoleKey)ocv.UserInterface.waitKey(30);
                if (Console.KeyAvailable)
                {
                    key = Console.ReadKey().Key;
                }
                threshold.Dispose();
            } while (key != ConsoleKey.Escape);

            ocv.UserInterface.destroyAllWindows();
            frame.Dispose();
            capture.release();
            ct.Close();
            Console.WriteLine("Program end");
        }
    }
}
