using PlcSiemens.O;
using PlcSiemens.Protocol.Common;

namespace PlcSiemens.Protocol.Header
{
    public class HeaderPacket
    {
        public byte P { get; set; }        // Telegram ID, always 32
        public byte PduType { get; set; }  // Header type 1 or 7
        public ushort AbEx { get; set; }    // AB currently unknown, maybe it can be used for long numbers.
        public ushort Sequence { get; set; }// Message ID. This can be used to make sure a received answer
        public ushort ParLen { get; set; }   // Length of parameters which follow this header
        public ushort DataLen { get; set; }  // Length of data which follow the parameters

        public ushort PacketLength
        { get { return 0x0A; } }

        public virtual void Build(ByteBuffer buffer)
        {
            P = buffer.PopByte();
            PduType = buffer.PopByte();
            AbEx = buffer.PopUshort();
            Sequence = buffer.PopUshort();
            ParLen = buffer.PopUshort(); //ReqFunNegotiateParams自身数据长度 不包含head的
            DataLen = buffer.PopUshort();
        }

        public void Build(PduType pduType, ushort parLen, ushort dataLen)
        {
            P = 0x32;
            PduType = (byte)pduType;
            AbEx = 0x0000;
            Sequence = GetNextWord();
            ParLen = parLen;
            DataLen = dataLen;
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(P);
            buffer.Push(PduType);
            buffer.Push(AbEx);
            buffer.Push(Sequence);
            buffer.Push(ParLen);
            buffer.Push(DataLen);
        }

        private static ushort _cntword = 1;

        protected static ushort GetNextWord()
        {
            if (_cntword == 0xFFFF)
                _cntword = 1;
            return _cntword++;
        }
    }
}
