
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 Command17
    implements Command<Command17.Result>
{
    public static final String tag = "cmd_17";
    public static final String typeName = "17 Report Slave ID";

    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 [] data;
        private final ModbusException exception;
        private final long responseTime;

        Result (Numeric.Value [] data, ModbusException exception,
            long responseTime)
        {
            assert data != null;
            this.data = data.clone ();
            this.exception = exception;
            this.responseTime = responseTime;
        }

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

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

        public Numeric.Value [] getData ()
        {
            return data.clone ();
        }

        @Override
        public boolean matches (Command.Result obj)
        {
            Command17.Result r = (Command17.Result) obj;
            if (r.exception != null)
                return r.exception.matches (exception);
            if (exception != null)
                return false;
            return Numeric.matches (r.data, data);
        }

        @Override
        public boolean equals (Object obj)
        {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (obj.getClass () != getClass ())
                return false;
            Command17.Result r = (Command17.Result) obj;
            if (r.exception != null)
                return r.exception.equals (exception);
            if (exception != null)
                return false;
            if (!Arrays.equals (r.data, data))
                return false;
            return true;
        }

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

    Command17 (String name, String description, int slaveId,
        ModbusException exception, Numeric.Value [] data)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        expectedResult = new Result (data, exception, 0);
        actualResult = null;
    }

    Command17 (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;
        Command17 cmd = (Command17) 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;
    }

    private boolean isAscii (byte [] data)
    {
        for (int i = 0 ; i < data.length ; i++)
        {
            byte b = data [i];
            if (b < 0x20 || b >= 0x7f)
                return false;
        }

        return true;
    }

    public void send (ModbusClient client, Settings settings)
        throws InterruptedException, IOException, ValueException
    {
        try
        {
            ModbusTransaction trans = client.createTransaction (slaveId,
                Modbus.FUNC_REPORT_SLAVE_ID, 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 (1);
            int len = response.getByte (0);
            GeneralSettings gs = settings.getGeneral ();
            if (gs.getAllowLongMessages ().getValue ())
            {
                len = response.size () - 1;
            }
            else if (gs.getStrictChecking ().getValue ())
            {
                response.checkSize (len + 1);
            }
            byte [] a = response.getData (1, len);
            actualResult = new Result (Numeric.fromByteArray (a), null,
                trans.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = new Result (new Numeric.Value [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 ("data", expectedResult.data, 16);
            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 [] data;
        private ModbusException exception;

        XmlLoader (Xml.Receiver<Command> receiver, boolean isTester)
        {
            this.receiver = receiver;
            this.isTester = isTester;
            name = "";
            description = "";
            slaveId = 1;
            compareData = true;
            data = 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 ("data"))
                        {
                            return new Xml.NumericArrayLoader (
                                Numeric.Type.uint8, 16, true,
                                new Xml.Receiver<Numeric.Value []> ()
                                {
                                    public void receive (Numeric.Value [] value)
                                    {
                                        data = 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 (data == null || exception != null || !compareData)
                    data = new Numeric.Value [0];
                Command17 command = new Command17 (name, description, slaveId,
                    exception, data);
                receiver.receive (command);
            }
            else
            {
                Command17 command = new Command17 (name, description, slaveId);
                receiver.receive (command);
            }
        }
    }
}

