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

namespace PlcSiemens.Protocol.ListBlocks
{
    public class DataBlockInfoDataRequest
    {
        public byte Ret { get; set; }
        public byte Size { get; set; }
        public ushort DataLen { get; set; }
        public byte BlkPrfx { get; set; }     // always 0x30
        public byte BlkType { get; set; }
        public byte[] AsciiBlk { get; set; } // BlockNum in ascii
        public byte A { get; set; }

        public ushort PacketLength
        { get { return (ushort)(7 + AsciiBlk.Length); } }

        public void Build(BlockType blockType, ushort db)
        {
            Ret = 0xFF;
            Size = (byte)TsType.TsResOctet;
            DataLen = 0x0008;
            BlkPrfx = 0x30;
            BlkType = (byte)blockType;
            AsciiBlk = new byte[5];

            AsciiBlk[0] = (byte)((db / 10000) + 0x30);
            db = (ushort)(db % 10000);
            AsciiBlk[1] = (byte)((db / 1000) + 0x30);
            db = (ushort)(db % 1000);
            AsciiBlk[2] = (byte)((db / 100) + 0x30);
            db = (ushort)(db % 100);
            AsciiBlk[3] = (byte)((db / 10) + 0x30);
            db = (ushort)(db % 10);
            AsciiBlk[4] = (byte)((db / 1) + 0x30);
            A = 0x41;
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(Ret);
            buffer.Push(Size);
            buffer.Push(DataLen);
            buffer.Push(BlkPrfx);
            buffer.Push(BlkType);
            buffer.Push(AsciiBlk);
            buffer.Push(A);
        }
    }
}
