using Microsoft.Kinect;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Lib
{
    public class ColorImageStream : KinectStream
    {
        private ColorFrameReader reader;
        public ColorFrameReader Reader { 
            get { 
                return reader;
            }
            set
            {
                reader = value;
            }
        }
        public ColorImageStream(KinectManager kinectManager) : base(kinectManager)
        {
            var frameDescription = KinectManager.Sensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
            this.Bitmap = new WriteableBitmap(frameDescription.Width, frameDescription.Height, 96.0, 96.0, PixelFormats.Bgr32, null);
            reader = KinectManager.Sensor.ColorFrameSource.OpenReader();
            reader.FrameArrived += Reader_ColorFrameArrived;
        }

        public override void Stop()
        {
            if (reader != null)
            {
                reader.Dispose();
                reader = null;
            }
        }

        private void Reader_ColorFrameArrived(object sender, ColorFrameArrivedEventArgs e)
        {
            using (ColorFrame colorFrame = e.FrameReference.AcquireFrame())
            {
                if (colorFrame != null)
                {
                    // ... Logique existante pour traiter la frame
                    //Debug.WriteLine("Traitement de la frame de couleur.");
                    FrameDescription colorFrameDescription = colorFrame.FrameDescription;

                    using (KinectBuffer colorBuffer = colorFrame.LockRawImageBuffer())
                    {
                        this.Bitmap.Lock();

                        // Vérifier si la taille de l'image a changé
                        if ((colorFrameDescription.Width == this.Bitmap.PixelWidth) && (colorFrameDescription.Height == this.Bitmap.PixelHeight))
                        {
                            colorFrame.CopyConvertedFrameDataToIntPtr(
                                this.Bitmap.BackBuffer,
                                (uint)(colorFrameDescription.Width * colorFrameDescription.Height * 4),
                                ColorImageFormat.Bgra);

                            this.Bitmap.AddDirtyRect(new Int32Rect(0, 0, this.Bitmap.PixelWidth, this.Bitmap.PixelHeight));
                        }

                        this.Bitmap.Unlock();
                    }
                    //Debug.WriteLine("Frame de couleur traitée.");
                }
            }
        }
    }
}
