using System;
using System.IO;

namespace Inspectron.HawkEye.UDPB
{
    public class UDPBPacket
    {

        public enum EPacketType:uint
        {
            Data=0,
            CloseSequence=1,
            BeginSequence=2,
            Nak=3,
            Ok=4
        }

        public UDPBPacket()
        {
        }

        private const int sequenceIndex = 0;
        private const int messageIndex = 1;
        private const int typeIndex = 2;
        private const int datalengthIndex = 3;

        public const int packetHeaderSize = 16;

        private uint[] _header=new uint[4];

        public uint SequenceId
        {
            get => _header[sequenceIndex];
            set => _header[sequenceIndex] = value;
        }

        public uint MessageId
        {
            get => _header[messageIndex];
            set => _header[messageIndex] = value;
        }

        public EPacketType Type
        {
            get => (EPacketType)_header[typeIndex];
            set => _header[typeIndex] = (uint)value;
        }

        private byte[] _payload;

        public byte[] Payload
        {
            get => _payload??new byte[0];
            set
            {
                _payload = value;
            }
        }
        public uint Length
        {
            get => _header[datalengthIndex];
            set => _header[datalengthIndex] = value;
        }


        public byte[] Serialize()
        {
            
            byte[] bytes = new byte[UDPBQueue.PACKET_SIZE+packetHeaderSize];
            Buffer.BlockCopy(_header, 0, bytes, 0, packetHeaderSize);
            if(_payload!=null)
                Array.Copy(_payload, 0, bytes, packetHeaderSize, _payload.Length);
            return bytes;
        }

        public void Deserialize(byte[] data,int offset,int len)
        {

            Buffer.BlockCopy(data, offset, _header, 0, packetHeaderSize);
            var dataLen = _header[datalengthIndex];
            if (dataLen > 0)
            {
                _payload = new byte[dataLen];


                Array.Copy(data, packetHeaderSize+ offset, _payload, 0, (int) dataLen);
            }

        }
    }
}