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

namespace PlcSiemens.Protocol.Upload
{
    public class StartUploadParamsRequest
    {
        public byte FunSUpld;    // function start upload 0x1D
        public byte[] Uk6;     // Unknown 6 bytes
        public byte UploadID;// At begining is 0) we will put upload id incoming from plc
        public byte Len1;
        public byte Prefix;
        public byte BlkPrfx;     // always 0x30
        public byte BlkType;
        public byte[] AsciiBlk; // BlockNum in ascii
        public byte A;           // always 0x41 ('A')

        public ushort PacketLength
        {
            get
            {
                return 0x12;
            }
        }

        public void GetByteBuffer(ByteBuffer buffer)
        {
            buffer.Push(FunSUpld);
            buffer.Push(Uk6);
            buffer.Push(UploadID);
            buffer.Push(Len1);
            buffer.Push(Prefix);
            buffer.Push(BlkPrfx);
            buffer.Push(BlkType);
            buffer.Push(AsciiBlk);
            buffer.Push(A);
        }

        public void Build(BlockType blockType, ushort blockNum)
        {
            FunSUpld = (byte)PduFuncType.PduStartUpload;
            byte byte00 = 0x00;
            Uk6 = new[] { byte00, byte00, byte00, byte00, byte00, byte00 };
            UploadID = 0x00;
            Len1 = 0x09;
            Prefix = 0x5F;
            BlkPrfx = 0x30; // '0'
            BlkType = (byte)blockType;

            int tmp = blockNum;
            AsciiBlk = new byte[5];
            AsciiBlk[0] = (byte)((tmp / 10000) + 0x30);
            tmp = tmp % 10000;
            AsciiBlk[1] = (byte)((tmp / 1000) + 0x30);
            tmp = tmp % 1000;
            AsciiBlk[2] = (byte)((tmp / 100) + 0x30);
            tmp = tmp % 100;
            AsciiBlk[3] = (byte)((tmp / 10) + 0x30);
            tmp = tmp % 10;
            AsciiBlk[4] = (byte)((tmp / 1) + 0x30);
            A = 0x41; // 'A'
        }
    }
}
