using PlcSiemens.Protocol.Common;
using PlcSiemens.Protocol.ReadData;
using ByteBuffer = PlcSiemens.O.ByteBuffer;

namespace PlcSiemens.Protocol.WriteData
{
    public class WriteDataRequest
    {
        public byte ReturnCode { get; set; }
        public byte TransportSize { get; set; }
        public ushort DataLength { get; set; }
        public byte[] Data { get; set; }// 17 = header + params + data header -1

        public ushort PacketLength
        { get { return (ushort)(0x04 + Data.Length); } }

        public void Build(DataItem item, bool isLast)
        {
            var sizeByte = (ushort)(item.SizeByte * item.Length);
            ReturnCode = 0x00;
            switch (item.DataType)
            {
                case DataType.Bit:
                    TransportSize = (byte)TsType.TsResBit; ;
                    break;

                case DataType.Int:
                case DataType.DInt:
                    TransportSize = (byte)TsType.TsResInt;
                    break;

                case DataType.Real:
                    TransportSize = (byte)TsType.TsResReal;// TS_ResReal;
                    break;

                case DataType.Char:
                case DataType.Counter:
                case DataType.Timer:
                    TransportSize = (byte)TsType.TsResOctet;//TS_ResOctet;
                    break;

                default:
                    TransportSize = (byte)TsType.TsResByte;
                    break;
            };
            if ((TransportSize != (byte)TsType.TsResOctet) &&
                (TransportSize != (byte)TsType.TsResReal) &&
                (TransportSize != (byte)TsType.TsResBit))
                DataLength = (ushort)(sizeByte * 8);
            else
                DataLength = (sizeByte);
            if (!isLast && sizeByte % 2 != 0)
                Data = new byte[sizeByte + 1];
            else
                Data = new byte[sizeByte];
            Array.Copy(item.Data, item.DataOffset, Data, 0, sizeByte);
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(ReturnCode);
            buffer.Push(TransportSize);
            buffer.Push(DataLength);
            buffer.Push(Data);
        }
    }
}
