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

namespace PlcSiemens.Protocol.WriteData
{
    public class WriteRequest : IBuildRequest
    {
        public HeaderPacket Header { get; set; }
        public WriteParamsRequest Params { get; set; }
        public WriteDataRequest[] Data { get; set; }
        public List<DataItem> DataItems { get; set; }

        public WriteRequest()
        {
            Header = new HeaderPacket();
            Params = new WriteParamsRequest();
        }

        public void Build()
        {
            Params.Build(DataItems);
            Data = new WriteDataRequest[DataItems.Count];
            ushort dataLength = 0;
            for (int i = 0; i < DataItems.Count; i++)
            {
                var tmp = new WriteDataRequest();
                Data[i] = tmp;
                var dataItem = DataItems[i];
                tmp.Build(dataItem, i == DataItems.Count - 1);
                dataLength += tmp.PacketLength;
            }

            ushort paramsLength = Params.PacketLength;

            Header.Build(PduType.Request, paramsLength, dataLength);
        }

        public ByteBuffer GetBuffer()
        {
            ByteBuffer buffer = ByteBuffer.Allocate();
            Header.GetByteBuffer(buffer);
            Params.GetByteBuffer(buffer);
            Data.ForEach(t => t.GetByteBuffer(buffer));
            return buffer;
        }
    }
}
