using System;

namespace SharpModbus
{
    public class ModbusF04ReadInputRegisters : IModbusCommand
    {
        private readonly byte slave;
        private readonly ushort address;
        private readonly ushort count;

        public byte Code { get { return 4; } }
        public byte Slave { get { return slave; } }
        public ushort Address { get { return address; } }
        public ushort Count { get { return count; } }
        public int RequestLength { get { return 6; } }
        public int ResponseLength { get { return 3 + ModbusUtils.BytesForWords(count); } }

        public ModbusF04ReadInputRegisters(byte slave, ushort address, ushort count)
        {
            this.slave = slave;
            this.address = address;
            this.count = count;
        }

        public void FillRequest(byte[] request, int offset)
        {
            request[offset + 0] = slave;
            request[offset + 1] = 4;
            request[offset + 2] = ModbusUtils.High(address);
            request[offset + 3] = ModbusUtils.Low(address);
            request[offset + 4] = ModbusUtils.High(count);
            request[offset + 5] = ModbusUtils.Low(count);
        }

        public object ParseResponse(byte[] response, int offset)
        {
            var bytes = ModbusUtils.BytesForWords(count);
            Tools.AssertEqual(response[offset + 0], slave, "Slave mismatch got {0} expected {1}");
            Tools.AssertEqual(response[offset + 1], 4, "Function mismatch got {0} expected {1}");
            Tools.AssertEqual(response[offset + 2], bytes, "Bytes mismatch got {0} expected {1}");
            return ModbusUtils.DecodeWords(response, offset + 3, count);
        }

        public object ApplyTo(IModbusModel model)
        {
            return model.getWIs(slave, address, count);
        }

        public void FillResponse(byte[] response, int offset, object value)
        {
            var bytes = ModbusUtils.BytesForWords(count);
            response[offset + 0] = slave;
            response[offset + 1] = 4;
            response[offset + 2] = bytes;
            var data = ModbusUtils.EncodeWords(value as ushort[]);
            ModbusUtils.Copy(data, 0, response, offset + 3, bytes);
        }

        public override string ToString()
        {
            return string.Format("[ModbusF04ReadInputRegisters Slave={0}, Address={1}, Count={2}]", slave, address, count);
        }
    }
}