
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.*;
import uk.co.wingpath.io.*;

public class CommandRaw
    implements Command<CommandRaw.Result>
{
    public static final String tag = "cmd_raw";
    public static final String typeName = "Send Raw Data";
    public static final int MAX_BYTES = Modbus.MAX_IMP_PDU_SIZE + 7;

    private final String name;
    private final String description;

    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)
        {
            CommandRaw.Result r = (CommandRaw.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;
            CommandRaw.Result r = (CommandRaw.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;
        }
    }

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

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

    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;
        CommandRaw cmd = (CommandRaw) obj;
        if (!cmd.name.equals (name))
            return false;
        if (!cmd.description.equals (description))
            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 + 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
        {
            Tracer tracer = client.getTracer ();
            byte [] buf = new byte [MAX_BYTES];

            for (int i = 0 ; i < sendData.length ; i++)
                buf [i] = (byte) sendData [i].getLongValue ();

            int preTimeout =
                settings.getGeneral ().getReplyTimeout ().getValue ();
            int eomTimeout =
                settings.getSlaveInterface ().getEomTimeout ();
            long timeStart = System.nanoTime ();
            int bytesRead = 0;

            try
            {
                Connection connection = client.seizeConnection ();
                connection.write (buf, 0, sendData.length);
                if (tracer != null)
                    tracer.traceRaw (">", buf, 0, sendData.length);

                for (;;)
                {
                    try
                    {
                        int n = connection.read (buf, bytesRead,
                            buf.length - bytesRead,
                            bytesRead == 0 ? preTimeout : eomTimeout,
                            bytesRead == 0);
                        if (n == 0)
                            break;
                        if (tracer != null)
                            tracer.traceRaw ("<", buf, bytesRead, n);
                        bytesRead += n;
                    }
                    catch (InterruptedIOException e)
                    {
                        if (bytesRead != 0)
                            break;
                        throw e;
                    }
                }
            }
            finally
            {
                client.releaseConnection ();
            }
            if (tracer != null)
                tracer.endTransaction ();
            Numeric.Value [] receiveData =
                Numeric.Type.uint8.createUndefArray (bytesRead);

            for (int i = 0 ; i < bytesRead ; i++)
                receiveData [i] = Numeric.Type.uint8.createValue (buf [i]);

            actualResult = new Result (receiveData, null,
                System.nanoTime () - timeStart);
        }
        catch (HInterruptedIOException e)
        {
            actualResult = new Result (new Numeric.Value [0],
                new ModbusException (
                    Modbus.ERROR_TIMED_OUT,
                    e.getHelpId (),
                    e.getMessage ()), 0);
        }
        catch (RecoverableIOException e)
        {
            actualResult = new Result (new Numeric.Value [0],
                new ModbusException (
                    Modbus.ERROR_TIMED_OUT,
                    e.getHelpId (),
                    e.getMessage ()), 0);
        }
        catch (InterruptedIOException e)
        {
            actualResult = new Result (new Numeric.Value [0],
                new ModbusException (
                    Modbus.ERROR_TIMED_OUT,
                    "MI120",
                    e.getMessage ()), 0);
        }
    }

    public void save (Xml.Saver saver)
        throws IOException
    {
        saver.saveValue ("name", name);
        saver.saveValue ("description", description);
        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 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 = "";
            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 ("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];
                CommandRaw command = new CommandRaw (name, description,
                    sendData, exception, receiveData);
                receiver.receive (command);
            }
            else
            {
                CommandRaw command = new CommandRaw (name, description,
                    sendData);
                receiver.receive (command);
            }
        }
    }
}

