using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using OpenNI;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Threading;

namespace Kinect_viewer.Projection
{   /// <summary>
    /// Image_projection is derrived form AProjection class a nd implements methods of IProjection interface
    /// </summary>
    public delegate void ggg();
    internal class Image_projection : AProjection, IProjection
    {
        private Form1 form;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="form"></param>
        public Image_projection(Form1 form)
            : base()
        {
            this.form = form;
        }

        public unsafe void ReaderThread()
        {
            imageMD = new ImageMetaData();
            while (this.ShouldRun)
            {
                try
                {
                    this.context.WaitAnyUpdateAll();
                }
                catch (Exception e)
                {
                    throw e;
                }
                this.image.GetMetaData(imageMD);
                lock (imageBitmap)
                {
                    // Debug.WriteLine(depthMD[153280].ToString());
                    Rectangle imageRect = new Rectangle(0, 0, ImageBitmap.Width, ImageBitmap.Height);
                    BitmapData imageData = ImageBitmap.LockBits(imageRect, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    byte* pSrc = (byte*)image.ImageMapPtr.ToPointer();

                    for (int y = 0; y < imageMD.YRes; ++y)
                    {//Scan0 vrátí hodnotu prvního řádku a stride postupně načte všechny řádky
                        byte* pDest2 = (byte*)imageData.Scan0.ToPointer() + y * imageData.Stride;
                        for (int x = 0; x < imageMD.XRes; ++x, pDest2 += 3, pSrc += 3)
                        {//Setting projection color
                            //Image 
                            pDest2[0] = pSrc[2];
                            pDest2[1] = pSrc[1];
                            pDest2[2] = pSrc[0];
                        }
                    }
                    this.ImageBitmap.UnlockBits(imageData);
                    ((Form1)form).SetImageToDraw(this.ImageBitmap);
                }
                
                Thread.Sleep(200);
                
            }
        }
    }
}
