
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 CommandCustom
    implements Command<CommandCustom.Result>
{
    public static final String tag = "cmd_custom";
    public static final String typeName = "Custom Command";

    private final String name;
    private final String description;

    private final int slaveId;
    private final int function;
    private final Numeric.Value [] sendData;

    private Result actualResult;
    private final Result expectedResult;

    public class Result
        implements Command.Result
    {
        private final Numeric.Value [] receiveData;
        private final ModbusException exception;
        private final long responseTime;

        Result (Numeric.Value [] receiveData, ModbusException exception,
            long responseTime)
        {
            this.receiveData = receiveData;
            this.exception = exception;
            this.responseTime = responseTime;
        }

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

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

        public Numeric.Value [] getReceiveData ()
        {
            return receiveData;
        }

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

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

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

    CommandCustom (String name, String description, int slaveId, int function,
        Numeric.Value [] sendData,
        ModbusException exception, Numeric.Value [] receiveData)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.function = function;
        this.sendData = sendData.clone ();
        expectedResult = new Result (receiveData, exception, 0);
        actualResult = null;
    }

    CommandCustom (String name, String description, int slaveId, int function,
        Numeric.Value [] sendData)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.function = function;
        this.sendData = sendData.clone ();
        expectedResult = null;
        actualResult = null;
    }

    public int getSlaveId ()
    {
        return slaveId;
    }

    public int getFunction ()
    {
        return function;
    }

    public Numeric.Value [] getSendData ()
    {
        return sendData;
    }

    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;
        CommandCustom cmd = (CommandCustom) obj;
        if (!cmd.name.equals (name))
            return false;
        if (!cmd.description.equals (description))
            return false;
        if (cmd.slaveId != slaveId)
            return false;
        if (cmd.function != function)
            return false;
        if (!Arrays.equals (cmd.sendData, sendData))
            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 + function;
        hash = 29 * hash + Arrays.hashCode (sendData);
        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,
                function, Numeric.toByteArray (sendData));
            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 ();
            actualResult =
                new Result (Numeric.fromByteArray (response.getData ()), 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);
        saver.saveValue ("function", function);
        saver.saveValue ("senddata", sendData, 16);
        if (expectedResult != null)
        {
            saver.startTag ("result");
            saver.saveValue ("receivedata", expectedResult.receiveData, 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 int function;
        private Numeric.Value [] sendData;
        private boolean compareData;
        private Numeric.Value [] receiveData;
        private ModbusException exception;

        XmlLoader (Xml.Receiver<Command> receiver, boolean isTester)
        {
            this.receiver = receiver;
            this.isTester = isTester;
            name = "";
            description = "";
            slaveId = 1;
            function = 0;
            sendData = null;
            compareData = true;
            receiveData = 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 ("function"))
            {
                return new Xml.IntegerLoader (0, 255,
                    new Xml.Receiver<Integer> ()
                    {
                        public void receive (Integer value)
                        {
                            function = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("senddata"))
            {
                return new Xml.NumericArrayLoader (
                    Numeric.Type.uint8, 16, true,
                    new Xml.Receiver<Numeric.Value []> ()
                    {
                        public void receive (Numeric.Value [] value)
                        {
                            sendData = 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 ("receivedata"))
                        {
                            return new Xml.NumericArrayLoader (
                                Numeric.Type.uint8, 16, true,
                                new Xml.Receiver<Numeric.Value []> ()
                                {
                                    public void receive (Numeric.Value [] value)
                                    {
                                        receiveData = 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 (sendData == null)
                throw new ValueException ("<senddata> missing");
            if (isTester)
            {
                if (receiveData == null || exception != null || !compareData)
                    receiveData = new Numeric.Value [0];
                CommandCustom command = new CommandCustom (name, description,
                    slaveId, function, sendData, exception, receiveData);
                receiver.receive (command);
            }
            else
            {
                CommandCustom command = new CommandCustom (name, description,
                    slaveId, function, sendData);
                receiver.receive (command);
            }
        }
    }
}

