
package uk.co.wingpath.modbusgui;

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

public class Command11
    implements Command<Command11.Result>
{
    public static final String tag = "cmd_11";
    public static final String typeName = "11 Get Comm Event Counter";

    private final String name;
    private final String description;

    private final int slaveId;

    private Result actualResult;
    private final Result expectedResult;

    public class Result
        implements Command.Result
    {
        private final Numeric.PatVal status;
        private final Numeric.PatVal count;
        private final ModbusException exception;
        private final long responseTime;

        Result (Numeric.PatVal status, Numeric.PatVal count,
            ModbusException exception, long responseTime)
        {
            this.status = status;
            this.count = count;
            this.exception = exception;
            this.responseTime = responseTime;
        }

        @Override
        public ModbusException getException ()
        {
            return exception;
        }

        @Override
        public long getResponseTime ()
        {
            return responseTime;
        }

        public Numeric.Value getActualStatus ()
        {
            return (Numeric.Value) status;
        }

        public Numeric.Pattern getExpectedStatus ()
        {
            return (Numeric.Pattern) status;
        }

        public Numeric.Value getActualCount ()
        {
            return (Numeric.Value) count;
        }

        public Numeric.Pattern getExpectedCount ()
        {
            return (Numeric.Pattern) count;
        }

        @Override
        public boolean matches (Command.Result obj)
        {
            Command11.Result r = (Command11.Result) obj;
            if (exception != null)
                return exception.matches (r.exception);
            if (r.exception != null)
                return false;
            Numeric.Pattern ps = (Numeric.Pattern) status;
            Numeric.Pattern pc = (Numeric.Pattern) count;
            return ps.matches ((Numeric.Value) r.status) &&
                pc.matches ((Numeric.Value) r.count);
        }

        @Override
        public boolean equals (Object obj)
        {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (obj.getClass () != getClass ())
                return false;
            Command11.Result r = (Command11.Result) obj;
            if (r.exception != null)
                return r.exception.equals (exception);
            if (exception != null)
                return false;
            {
                if (!r.status.equals (status))
                    return false;
                if (!r.count.equals (count))
                    return false;
            }
            return true;
        }

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

    Command11 (String name, String description, int slaveId,
        ModbusException exception,
        Numeric.Pattern status, Numeric.Pattern count)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        expectedResult = new Result (status, count, exception, 0);
        actualResult = null;
    }

    Command11 (String name, String description, int slaveId)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        expectedResult = null;
        actualResult = null;
    }

    public int getSlaveId ()
    {
        return slaveId;
    }

    public Result getActualResult ()
    {
        return actualResult;
    }

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

    public Result 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;
        Command11 cmd = (Command11) obj;
        if (!cmd.name.equals (name))
            return false;
        if (!cmd.description.equals (description))
            return false;
        if (cmd.slaveId != slaveId)
            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;
        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
        {
            ModbusTransaction trans = client.createTransaction (slaveId,
                Modbus.FUNC_GET_COMM_EVENT_COUNTER, new byte [] {});
            client.handleTransaction (trans);
            assert trans.isFinished () : trans.getState ();
            Tracer tracer = client.getTracer ();
            if (tracer != null)
                tracer.endTransaction ();
            ModbusException exception = trans.getException ();
            if (exception != null)
                throw exception;
            ModbusMessage response = trans.getResponse ();
            if (settings.getGeneral ().getStrictChecking ().getValue ())
                response.checkSize (4);
            else
                response.checkMinSize (4);
            actualResult = new Result (
                Numeric.Type.uint16.createValue (response.getInt (0)),
                Numeric.Type.uint16.createValue (response.getInt (2)),
                null, trans.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = new Result (Numeric.Type.uint16.undef,
                Numeric.Type.uint16.undef, e, 0);
        }
    }

    public void save (Xml.Saver saver)
        throws IOException
    {
        saver.saveValue ("name", name);
        saver.saveValue ("description", description);
        saver.saveValue ("slaveid", slaveId);
        if (expectedResult != null)
        {
            saver.startTag ("result");
            saver.saveValue ("status",
                (Numeric.Pattern) expectedResult.status, 10);
            saver.saveValue ("count",
                (Numeric.Pattern) expectedResult.count, 10);
            if (expectedResult.exception != null)
                CommandResult.saveException (saver, expectedResult.exception);
            saver.endTag ("result");
        }
    }

    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 boolean compareData;
        private Numeric.Pattern status;
        private Numeric.Pattern count;
        private ModbusException exception;

        XmlLoader (Xml.Receiver<Command> receiver, boolean isTester)
        {
            this.receiver = receiver;
            this.isTester = isTester;
            name = "";
            description = "";
            slaveId = 1;
            compareData = true;
            status = Numeric.Type.uint16.emptyPattern;
            count = Numeric.Type.uint16.emptyPattern;
            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 ("comparevalues"))
            {
                return new Xml.BooleanLoader (new Xml.Receiver<Boolean> ()
                {
                    public void receive (Boolean value)
                        throws ValueException
                    {
                        compareData = value;
                    }
                });
            }

            if (tag.equalsIgnoreCase ("result"))
            {
                return new Xml.AbstractLoader ()
                {
                    @Override
                    public Xml.Loader startChild (String tag)
                    {
                        if (tag.equalsIgnoreCase ("status"))
                        {
                            return new Xml.NumericPatternLoader (
                                Numeric.Type.uint16, 10,
                                new Xml.Receiver<Numeric.Pattern> ()
                                {
                                    public void receive (Numeric.Pattern value)
                                    {
                                        status = value;
                                    }
                                });
                        }

                        if (tag.equalsIgnoreCase ("count"))
                        {
                            return new Xml.NumericPatternLoader (
                                Numeric.Type.uint16, 10,
                                new Xml.Receiver<Numeric.Pattern> ()
                                {
                                    public void receive (Numeric.Pattern value)
                                    {
                                        count = value;
                                    }
                                });
                        }

                        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 value)
            throws ValueException
        {
            if (!value.equals (""))
                throw new ValueException ("Value not allowed");
            if (name.equals (""))
                throw new ValueException ("<name> missing");
            if (isTester)
            {
                if (exception != null || !compareData)
                {
                    status = Numeric.Type.uint16.emptyPattern;
                    count = Numeric.Type.uint16.emptyPattern;
                }
                Command11 command = new Command11 (name, description, slaveId,
                    exception, status, count);
                receiver.receive (command);
            }
            else
            {
                Command11 command = new Command11 (name, description, slaveId);
                receiver.receive (command);
            }
        }
    }
}
