
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 Command12
    implements Command<Command12.Result>
{
    public static final String tag = "cmd_12";
    public static final String typeName = "12 Get Comm Event Log";

    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.Value status;
        private final Numeric.Value eventCount;
        private final Numeric.Value msgCount;
        private final Numeric.Value [] events;
        private final ModbusException exception;
        private final long responseTime;

        Result (Numeric.Value status, Numeric.Value eventCount,
            Numeric.Value msgCount, Numeric.Value [] events,
            ModbusException exception, long responseTime)
        {
            this.status = status;
            this.eventCount = eventCount;
            this.msgCount = msgCount;
            this.events = events.clone ();
            this.exception = exception;
            this.responseTime = responseTime;
        }

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

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

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

        public Numeric.Value getEventCount ()
        {
            return eventCount;
        }

        public Numeric.Value getMsgCount ()
        {
            return msgCount;
        }

        public Numeric.Value [] getEvents ()
        {
            return events.clone ();
        }

        @Override
        public boolean matches (Command.Result obj)
        {
            Command12.Result r = (Command12.Result) obj;
            if (r.exception != null)
                return r.exception.matches (exception);
            if (exception != null)
                return false;
            if (!status.matches (r.status))
                return false;
            if (!eventCount.matches (r.eventCount))
                return false;
            if (!msgCount.matches (r.msgCount))
                return false;
            for (int i = 0 ; i < events.length ; ++i)
            {
                if (i < r.events.length)
                {
                    if (!events [i].matches (r.events [i]))
                        return false;
                }
                else
                {
                    if (events [i].isDefined ())
                        return false;
                }
            }
            return true;
        }

        @Override
        public boolean equals (Object obj)
        {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (obj.getClass () != getClass ())
                return false;
            Command12.Result r = (Command12.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.eventCount.equals (eventCount))
                return false;
            if (!r.msgCount.equals (msgCount))
                return false;
            if (!Arrays.equals (r.events, events))
                return false;
            return true;
        }

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

    Command12 (String name, String description, int slaveId,
        ModbusException exception, Numeric.Value status,
        Numeric.Value eventCount, Numeric.Value msgCount,
        Numeric.Value [] events)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        expectedResult =
            new Result (status, eventCount, msgCount, events, exception, 0);
        actualResult = null;
    }

    Command12 (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;
        Command12 cmd = (Command12) 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_LOG, 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 ();
            response.checkMinSize (7);
            int nbytes = response.getByte (0);
            if (nbytes < 6)
            {
                Modbus.dataError ("M120", "Byte count too small: " + nbytes +
                    " when expecting at least 6");
            }
            if (nbytes > 70)
            {
                Modbus.dataError ("M121", "Byte count too big: " + nbytes +
                    " when expecting at most 70");
            }
            if (settings.getGeneral ().getStrictChecking ().getValue ())
                response.checkSize (1 + nbytes);
            else
                response.checkMinSize (1 + nbytes);
            int status = response.getInt (1);
            int eventCount = response.getInt (3);
            int msgCount = response.getInt (5);
            byte [] events = response.getData (7, nbytes - 6);
            actualResult = new Result (
                Numeric.Type.uint16.createValue (status),
                Numeric.Type.uint16.createValue (eventCount),
                Numeric.Type.uint16.createValue (msgCount),
                Numeric.fromByteArray (events),
                null, trans.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = new Result (Numeric.Type.uint16.undef,
                Numeric.Type.uint16.undef, Numeric.Type.uint16.undef,
                Numeric.Type.uint8.createUndefArray (0), 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", expectedResult.status, 10);
            saver.saveValue ("eventCount", expectedResult.eventCount, 10);
            saver.saveValue ("msgCount", expectedResult.msgCount, 10);
            saver.saveValue ("events", expectedResult.events, 2);
            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.Value status;
        private Numeric.Value eventCount;
        private Numeric.Value msgCount;
        private Numeric.Value [] events;
        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.undef;
            eventCount = Numeric.Type.uint16.undef;
            msgCount = Numeric.Type.uint16.undef;
            events = 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 ("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.NumericLoader (
                                Numeric.Type.uint16, 10, true,
                                new Xml.Receiver<Numeric.Value> ()
                                {
                                    public void receive (Numeric.Value value)
                                    {
                                        status = value;
                                    }
                                });
                        }

                        if (tag.equalsIgnoreCase ("eventCount"))
                        {
                            return new Xml.NumericLoader (
                                Numeric.Type.uint16, 10, true,
                                new Xml.Receiver<Numeric.Value> ()
                                {
                                    public void receive (Numeric.Value value)
                                    {
                                        eventCount = value;
                                    }
                                });
                        }

                        if (tag.equalsIgnoreCase ("msgCount"))
                        {
                            return new Xml.NumericLoader (
                                Numeric.Type.uint16, 10, true,
                                new Xml.Receiver<Numeric.Value> ()
                                {
                                    public void receive (Numeric.Value value)
                                    {
                                        msgCount = value;
                                    }
                                });
                        }

                        if (tag.equalsIgnoreCase ("events"))
                        {
                            return new Xml.NumericArrayLoader (
                                Numeric.Type.uint8, 2, true,
                                new Xml.Receiver<Numeric.Value []> ()
                            {
                                public void receive (Numeric.Value [] value)
                                    throws ValueException
                                {
                                    if (value.length > 65535)
                                    {
                                        throw new ValueException (
                                            "Too many values (> 65535)");
                                    }
                                    events = 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.undef;
                    eventCount = Numeric.Type.uint16.undef;
                    msgCount = Numeric.Type.uint16.undef;
                }
                if (events == null || exception != null || !compareData)
                    events = Numeric.Type.uint8.createUndefArray (0);
                Command12 command = new Command12 (name, description, slaveId,
                    exception, status, eventCount, msgCount, events);
                receiver.receive (command);
            }
            else
            {
                Command12 command = new Command12 (name, description, slaveId);
                receiver.receive (command);
            }
        }
    }
}
