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

namespace PlcSiemens.Protocol.Iso
{
    public class IsoDataPdu
    {
        public TpktHeader Tpkt { get; set; } // TPKT Header
        public CotpDataHeader Cotp { get; set; }// COPT Header for DATA EXCHANGE
        public ushort Length { get; set; }

        public IsoDataPdu()
        {
            Tpkt = new TpktHeader();
            Cotp = new CotpDataHeader();
        }

        public void GetBuffer(ByteBuffer buffer)
        {
            Tpkt.GetByteBuffer(buffer);
            Cotp.GetByteBuffer(buffer);
        }

        public void Build()
        {
            Tpkt.Version = StaticConst.IsoTcpVersion;
            Tpkt.Reserved = 0;
            Tpkt.Length = (ushort)(Length + 0x07);

            Cotp.Length = (byte)(Cotp.PacketLength - 1);//去掉长度占用的一个字节
            Cotp.PduType = (byte)PduType.DataTransfer;
            Cotp.EoTNum = (byte)PduType.EndTransfer;
        }

        public void Build(ByteBuffer buffer)
        {
            Tpkt.Version = buffer.PopByte();
            Tpkt.Reserved = buffer.PopByte();
            Tpkt.Length = buffer.PopUshort();
            Length = Tpkt.Length;

            Cotp.Length = buffer.PopByte();
            Cotp.PduType = buffer.PopByte();
            Cotp.EoTNum = buffer.PopByte();
        }
    }
}
