
package uk.co.wingpath.modbusgui;

import java.io.*;
import java.util.*;
import uk.co.wingpath.event.*;
import uk.co.wingpath.util.*;
import uk.co.wingpath.xml.*;
import uk.co.wingpath.modbus.*;

public class Command6
    implements Command<CommandResult>
{
    public static final String tag = "cmd_6";
    public static final String typeName = "6 Write Single Holding Register";

    private final String name;
    private final String description;

    private final int slaveId;
    private final int address;
    private final Numeric.Type type;
    private final int radix;
    private final Numeric.Value value;

    private CommandResult actualResult;
    private final CommandResult expectedResult;

    private class Model
        extends ModbusModel
    {
        Model (BigValueFlags bigValueFlags)
        {
            super (bigValueFlags, null);
        }

        @Override
        public int getValueSize (int address)
        {
            return type.getSize ();
        }

        @Override
        public boolean isFloat (int address)
        {
            return type.isFloat ();
        }

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

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

        @Override
        public long getLongValue (int address)
        {
            return value.getLongValue ();
        }

        @Override
        public double getDoubleValue (int address)
        {
            return value.getDoubleValue ();
        }
    }

    Command6 (String name, String description, int slaveId, int address,
        Numeric.Type type, int radix, Numeric.Value value,
        ModbusException exception)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.address = address;
        this.type = type;
        this.radix = radix;
        this.value = value;
        expectedResult = CommandResult.create (exception);
        actualResult = null;
    }

    Command6 (String name, String description, int slaveId, int address,
        Numeric.Type type, int radix, Numeric.Value value)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.address = address;
        this.type = type;
        this.radix = radix;
        this.value = value;
        expectedResult = null;
        actualResult = null;
    }

    public int getSlaveId ()
    {
        return slaveId;
    }

    public int getAddress ()
    {
        return address;
    }

    public Numeric.Type getType ()
    {
        return type;
    }

    public int getRadix ()
    {
        return radix;
    }

    public Numeric.Value getValue ()
    {
        return value;
    }

    public CommandResult getActualResult ()
    {
        return actualResult;
    }

    public void setActualResult (CommandResult result)
    {
        actualResult = result;
    }

    public CommandResult getExpectedResult ()
    {
        return expectedResult;
    }

    @Override
    public boolean equals (Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (obj.getClass () != getClass ())
            return false;
        Command6 cmd = (Command6) obj;
        if (!cmd.name.equals (name))
            return false;
        if (!cmd.description.equals (description))
            return false;
        if (cmd.slaveId != slaveId)
            return false;
        if (cmd.address != address)
            return false;
        if (cmd.type != type)
            return false;
        if (cmd.radix != radix)
            return false;
        if (!cmd.value.equals (value))
            return false;
        if (expectedResult == null)
            return cmd.expectedResult == null;
        return expectedResult.equals (cmd.expectedResult);
    }

    @Override
    public int hashCode ()
    {
        int hash = 3;
        hash = 29 * hash + name.hashCode ();
        hash = 29 * hash + description.hashCode ();
        hash = 29 * hash + slaveId;
        hash = 29 * hash + address;
        hash = 29 * hash + type.hashCode ();
        hash = 29 * hash + radix;
        hash = 29 * hash + value.hashCode ();
        return hash;
    }

    @Override
    public String toString ()
    {
        return name;
    }

    public String getDescription ()
    {
        return description;
    }

    public String getTypeName ()
    {
        return typeName;
    }

    public String getTag ()
    {
        return tag;
    }

    public void send (ModbusClient client, Settings settings)
        throws InterruptedException, IOException, ValueException
    {
        try
        {
            BigValueFlags bigValueFlags = settings.getBigValue ().getValue ();
            GeneralSettings gs = settings.getGeneral ();
            int maxPdu = gs.getMaxPdu ().getValue ();
            boolean checkCountLimits =
                gs.getCheckCountLimits ().getValue ();
            boolean strictChecking = gs.getStrictChecking ().getValue ();
            boolean allowLongMessages = gs.getAllowLongMessages ().getValue ();
            ModbusMaster master = new ModbusMaster (
                new Model (bigValueFlags),
                client, slaveId, maxPdu, checkCountLimits,
                strictChecking, allowLongMessages, false);
            master.writeSingleRegister (address);
            actualResult = CommandResult.create (master.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = CommandResult.create (e);
        }
    }

    public void save (Xml.Saver saver)
        throws IOException
    {
        saver.saveValue ("name", name);
        saver.saveValue ("description", description);
        saver.saveValue ("slaveid", slaveId);
        saver.saveValue ("address", address);
        saver.saveValue ("type", type.toString ());
        saver.saveValue ("radix", RadixSelector.convertRadix (radix));
        saver.saveValue ("dvalue", value, 10);
        if (expectedResult != null)
            saver.saveValue ("result", expectedResult);
    }

    public static Xml.Loader getXmlLoader (Xml.Receiver<Command> receiver,
        boolean isTester)
    {
        return new XmlLoader (receiver, isTester);
    }

    private static class XmlLoader
        extends Xml.AbstractLoader
    {
        private final Xml.Receiver<Command> receiver;
        private final boolean isTester;
        private String name;
        private String description;
        private int slaveId;
        private int address;
        private Numeric.Type type;
        private int radix;
        private Numeric.Value value;
        private ModbusException exception;

        XmlLoader (Xml.Receiver<Command> receiver, boolean isTester)
        {
            this.receiver = receiver;
                this.isTester = isTester;
            name = "";
            description = "";
            slaveId = 1;
            address = 0;
            type = Numeric.Type.int16;
            radix = 10;
            value = null;
            exception = null;
        }

        @Override
        public Xml.Loader startChild (String tag)
        {
            if (tag.equalsIgnoreCase ("name"))
            {
                return new Xml.StringLoader (new Xml.Receiver<String> ()
                {
                    public void receive (String value)
                        throws ValueException
                    {
                        if (value.equals (""))
                            throw new ValueException ("Name missing");
                        name = value;
                    }
                });
            }

            if (tag.equalsIgnoreCase ("description"))
            {
                return new Xml.StringLoader (new Xml.Receiver<String> ()
                {
                    public void receive (String value)
                        throws ValueException
                    {
                        description = value;
                    }
                });
            }

            if (tag.equalsIgnoreCase ("slaveid"))
            {
                return new Xml.IntegerLoader (0, 255,
                    new Xml.Receiver<Integer> ()
                    {
                        public void receive (Integer value)
                        {
                            slaveId = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("address"))
            {
                return new Xml.IntegerLoader (0, 65535,
                    new Xml.Receiver<Integer> ()
                    {
                        public void receive (Integer value)
                        {
                            address = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("type"))
            {
                return new Xml.StringLoader (new Xml.Receiver<String> ()
                {
                    public void receive (String value)
                        throws ValueException
                    {
                        try
                        {
                            if (value.equals ("discrete"))
                            {
                                type = Numeric.Type.int1;
                            }
                            else
                            {
                                type = Numeric.Type.valueOf (value);
                            }
                        }
                        catch (IllegalArgumentException e)
                        {
                            throw new ValueException (e.getMessage ());
                        }
                    }
                });
            }

            if (tag.equalsIgnoreCase ("radix"))
            {
                return new Xml.StringLoader (new Xml.Receiver<String> ()
                {
                    public void receive (String value)
                        throws ValueException
                    {
                        if (!value.equals ("10"))
                        {
                            if (value.equals ("10U"))
                                value = "10";
                            type = type.unsigned ();
                        }
                        radix = RadixSelector.convertRadix (value);
                    }
                });
            }

            if (tag.equalsIgnoreCase ("dvalue"))
            {
                return new Xml.NumericLoader (type, 10, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value val)
                            throws ValueException
                        {
                            value = val;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("xvalue"))
            {
                return new Xml.NumericLoader (type, 16, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value val)
                            throws ValueException
                        {
                            value = val;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("value"))
            {
                return new Xml.NumericLoader (type, radix, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value val)
                            throws ValueException
                        {
                            value = val;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("result"))
            {
                return new Xml.AbstractLoader ()
                {
                    @Override
                    public Xml.Loader startChild (String tag)
                    {
                        if (tag.equalsIgnoreCase ("exception"))
                        {
                            return CommandResult.getExceptionLoader (
                                new Xml.Receiver<ModbusException> ()
                                {
                                    public void receive (ModbusException e)
                                    {
                                        exception = e;
                                    }
                                });
                        }

                        return null;
                    }
                };
            }

            return null;
        }

        public void end (String val)
            throws ValueException
        {
            if (!val.equals (""))
                throw new ValueException ("Value not allowed");
            if (name.equals (""))
                throw new ValueException ("<name> missing");
            if (value == null)
                throw new ValueException ("<value> missing");
            if (isTester)
            {
                Command6 command = new Command6 (name, description, slaveId,
                    address, type, radix, value, exception);
                receiver.receive (command);
            }
            else
            {
                Command6 command = new Command6 (name, description, slaveId,
                    address, type, radix, value);
                receiver.receive (command);
            }
        }
    }
}

