using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace EMDWebServer
{
    public class DataPool
    {
        #region Class variables
        // ----------------------------------------
        private static object LockObject = new object();

        private byte[] data;
        public ulong Counter { get; set; }
        public long Size { get; set; }
        // ----------------------------------------
        #endregion

        #region Public methods
        // ----------------------------------------
        public void setData(byte[] data)
        {
            try
            {
                Monitor.Enter(LockObject);

                if (this.Counter == ulong.MaxValue)
                    this.Counter = 0;

                if (this.Size != data.Length)
                    this.Size = data.Length;

                this.data = null;
                this.data = data;
                this.Counter++;

#if QUEUE_DEBUG
                Debug.WriteLine("Set:\t"+this.Counter);
#endif

                Monitor.PulseAll(LockObject);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            finally
            {
                Monitor.Exit(LockObject);
            }

        }

        public byte[] getData(ulong counter)
        {
            Monitor.Enter(LockObject);

            if (counter == this.Counter)
            {
                //Debug.WriteLine("Wait:\t" + counter);
                Monitor.Wait(LockObject);
            }

            byte[] copyData = new byte[this.data.Length];


            Array.Copy(this.data, copyData, this.data.Length);

#if QUEUE_DEBUG
            Debug.WriteLine("Get:\t" + counter);
#endif

            Monitor.Exit(LockObject);

            return copyData;
        }
        // ----------------------------------------
        #endregion
    }
}
