using System;
using System.Drawing;
using System.Windows.Forms;
using Euresys.EGrabber;

namespace displayLatestBuffer
{
    public partial class Form1 : Form
    {
        const int NB_BUFFERS = 50;

        EGenTL genTL = null;
        EGrabberDiscovery discovery = null;
        EGrabber grabber = null;
        System.Drawing.Bitmap bitmap = null;

        UInt64 imgWidth;
        UInt64 imgHeight;
        String imgFormat;

        System.Threading.Thread thread;
        volatile bool refreshThreadRunning = false;

        Euresys.EGrabber.Buffer currentBuffer = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
            refreshThreadRunning = false;
            if (grabber != null)
            {
                try
                {
                    grabber.Stop();
                }
                catch (System.Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
                grabber.CancelPop();
                while (thread.IsAlive)
                {
                    System.Threading.Thread.Sleep(100);
                }
                grabber.Dispose();
                grabber = null;
            }
            if (discovery != null)
            {
                discovery.Dispose();
                discovery = null;
            }
            if (genTL != null)
            {
                genTL.Dispose();
                genTL = null;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                genTL = new EGenTL();
                discovery = new EGrabberDiscovery(genTL);
                discovery.Discover();
                if (discovery.CameraCount == 0)
                {
                    throw new Exception("No cameras discovered");
                }
                grabber = new EGrabber(discovery.Cameras[0]);
                grabber.ReallocBuffers(NB_BUFFERS);
                imgWidth = grabber.Width;
                imgHeight = grabber.Height;
                imgFormat = grabber.PixelFormat;

                bitmap = new System.Drawing.Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                pictureBox1.Image = bitmap;

                grabber.Start();
                refreshThreadRunning = true;
                thread = new System.Threading.Thread(RefreshThread);
                thread.Start();

                timer1.Start();
            }
            catch (System.Exception exc)
            {
                MessageBox.Show(exc.Message);
                this.Close();
            }
        }

        delegate void InvalidateDelegate(bool invalidChildren);
        private void RefreshThread()
        {
            try
            {
                while (refreshThreadRunning && grabber != null)
                {
                    Euresys.EGrabber.Buffer buffer = new Euresys.EGrabber.Buffer(grabber);
                    if (!refreshThreadRunning)
                    {
                        break;
                    }
                    if (currentBuffer == null)
                    {
                        currentBuffer = buffer;
                    }
                    else
                    {
                        if (grabber != null)
                        {
                            buffer.Push();
                        }
                    }
                }
            }
            catch (GenTLError exc)
            {
                if (exc.GcError != GC_ERROR.GC_ERR_ABORT)
                {
                    MessageBox.Show(exc.Message);
                }
            }
            catch (System.Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (currentBuffer == null || grabber == null)
            {
                return;
            }

            if (currentBuffer == null || grabber == null)
            {
                return;
            }

            System.Drawing.Imaging.BitmapData bmpData = null;
            try
            {
                bmpData = bitmap.LockBits(new Rectangle(0, 0, (int)imgWidth, (int)imgHeight),
                    System.Drawing.Imaging.ImageLockMode.WriteOnly,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                currentBuffer.ConvertTo("BGR8", bmpData.Scan0, (ulong)(Math.Abs(bmpData.Stride) * bmpData.Height));
            }
            finally
            {
                if (bmpData != null)
                {
                    bitmap.UnlockBits(bmpData);
                }
            }
            pictureBox1.Refresh();

            Euresys.EGrabber.Buffer bufferTmp = currentBuffer;
            currentBuffer = null;
            if (grabber != null) {
                bufferTmp.Push();
            }
        }

    }
}
