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

namespace PlcSiemens.Protocol.ListBlocks
{
    public class DataBlockOfTypeRequest : IBuildRequest
    {
        public HeaderPacket Header { get; set; }
        public ParamsRequest Params { get; set; }
        public DataBlockOfTypeDataRequest Data { get; set; }

        public byte[] PadData { get; set; }

        public bool First = true;
        public BlockType BlockType { get; set; }
        public byte Seq = 0x00;

        public DataBlockOfTypeRequest()
        {
            Header = new HeaderPacket();
            Params = new ParamsRequest();
            Data = new DataBlockOfTypeDataRequest();
        }

        public void Build()
        {
            Params.Build(First, Seq, GrType.GrBlocksInfo, PduFuncType.SFunListBoT);
            PadData = null;
            ushort padLength = 0;
            if (!First)
            {
                PadData = new byte[] { 0x00, 0x00, 0x00, 0x00 };
                Params.Seq = Seq;
                padLength = 0x04;
            }
            Data.Build(First, BlockType);
            Header.Build(PduType.Userdata, (ushort)(Params.PacketLength + padLength), Data.PacketLength);
        }

        public ByteBuffer GetBuffer()
        {
            ByteBuffer buffer = ByteBuffer.Allocate();
            Header.GetByteBuffer(buffer);
            Params.GetByteBuffer(buffer);
            if (!PadData.IsNullOrEmpty())
                buffer.Push(PadData);
            Data.GetByteBuffer(buffer);
            return buffer;
        }
    }
}
