using System;
using System.Drawing;
using System.Threading;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace squirrowse.client
{
    public class Webcam
    {
        private static VideoCapture capture;
        private static Mat frame;
        private static Byte[] image;
        private static Thread camera;
        private static bool isCameraRunning;
        private readonly bool imagetakinginprogress = false;

        public Webcam(bool AutoActivate = true)
        {
            if (AutoActivate) Initalize();
        }

        public void Initalize()
        {
            CaptureCamera();
            isCameraRunning = true;
        }

        private void CaptureCamera()
        {
            camera = new Thread(CaptureCameraCallback);
            camera.Start();
        }

        private void CaptureCameraCallback()
        {
            Thread.Sleep(1);
            if (!isCameraRunning) return;
            frame = new Mat();
            capture = new VideoCapture(0);
            capture.Open(0);
            if (!capture.IsOpened()) return;
            while (isCameraRunning)
            {
                capture.Read(frame);
                image = frame.ToBytes();
            }
        }

        public byte[] GetBitmap()
        {
            if (!isCameraRunning) throw new Exception("Cannot take picutre if the camera is not initalized!");
            while (imagetakinginprogress)
            {
            }

            try
            {
                Thread.Sleep(100);
                return image;
                
            }
            catch
            {
                Thread.Sleep(100);
                return image;
            }
   
        }

        public void Deinitialize()
        {
            camera.Abort();
            capture.Release();
            isCameraRunning = false;
        }

        ~Webcam()
        {
            Deinitialize();
            capture.Dispose();
            frame.Dispose();
        }
    }
}