using System;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Controls;
using System.Threading.Tasks;
using System.Threading;

namespace FindIT
{
    public class Camera
    {
        private VideoCaptureDevice device;
        public VideoBrush videoBrush;
        private CaptureSource captureSource;
        public Canvas rectangle;

        public event Action OnFrameAvailable;

        public int[] pix2;

        public WriteableBitmap frame;

        public int[] FramePixels { get { return pix2; } set { pix2 = value; } }
        public WriteableBitmap Frame { get { return frame; } set { frame = value; } }

        public Camera(Canvas rect)
        {
            this.rectangle = rect;
            Ini();
        }

        public void Available()
        {
            OnFrameAvailable();
        }

        /// <summary>
        /// Останавливает процесс получения кадров из видеопотока
        /// </summary>
        public void Stop()
        {
            captureSource.Stop();
        }

        /// <summary>
        /// Инициализация
        /// </summary>
        public void Ini()
        {
            captureSource = new CaptureSource();
            device = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
            if (device != null)
            {
                videoBrush = new VideoBrush();
                videoBrush.SetSource(captureSource);
                rectangle.Background = videoBrush;
                captureSource.Start();
            }
            else
            {
                MainPage.main.Show("VideoCaptureDevice creating error");
            }
        }

        /// <summary>
        /// Запускает процесс получения кадров из видеопотока
        /// </summary>
        public void Start()
        {
            // MainPage.main.Show(captureSource.State.ToString() + " " + CaptureState.Failed.ToString() + " " + CaptureState.Started.ToString() + " " + CaptureState.Stopped.ToString());
            Task.Run(new Action(() =>
            {
                Thread.Sleep(2000);
                rectangle.Dispatcher.BeginInvoke(new Action(() => Ini()));
            }));
        }
    }
}
