
package uk.co.wingpath.modbusgui;

import java.util.*;
import uk.co.wingpath.util.ValueException;
import uk.co.wingpath.util.*;
import uk.co.wingpath.modbus.*;

public class CommandDiscreteModbusModel
    extends ModbusModel
{
    private final Numeric.Value [] data;
    private final int address;

    public CommandDiscreteModbusModel (int address, Numeric.Value [] data)
    {
        super (new BigValueFlags (false, false, false), null);
        this.address = address;
        this.data = data;
        AddressMap map = getAddressMap ();
        map.getCoilMap ().setSize (65536);
        // map.getCoilMap ().setMultiplier (1);
        map.getDiscreteInputMap ().setSize (65536);
        // map.getDiscreteInputMap ().setMultiplier (1);
    }

    @Override
    public int getValueSize (int address)
    {
        return 0;
    }

    @Override
    public boolean isSigned (int address)
        throws ModbusException
    {
        return false;
    }

    @Override
    public int getRadix (int address)
        throws ModbusException
    {
        return 10;
    }

    @Override
    public int getCoilValueSize ()
    {
        return 0;
    }

    @Override
    public int getDiscreteInputValueSize ()
    {
        return 0;
    }

    @Override
    public void setValue (int addr, long val)
        throws ModbusException
    {
        try
        {
// System.out.println ("setValue: addr " + addr + ", address " + address + ", length " + data.length);
            int row = addr - address;
            data [row] = Numeric.Type.int1.createValue (val);
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            // Address errors should not occur, so probably ought to throw an IllegalArgumentException
            Modbus.addressError (null, "No register at address " + addr);
        }
        catch (ValueException e)
        {
        }
    }

    public long getLongValue (int addr)
        throws ModbusException
    {
        try
        {
// System.out.println ("setValue: addr " + addr + ", address " + address + ", length " + data.length);
            int row = addr - address;
            return data [row].getLongValue ();
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            Modbus.addressError ("R101", "No register at address " + addr);
            throw new AssertionError ("Unreachable");
        }
    }
}

