
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 Command2
    implements Command<Command2.Result>
{
    public static final String tag = "cmd_2";
    public static final String typeName = "2 Read Discrete Inputs";

    private final String name;
    private final String description;

    private final int slaveId;
    private final int address;
    private final int count;

    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)
        {
            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 [] getActualData ()
        {
            return data.clone ();
        }

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

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

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

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

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

    public int getSlaveId ()
    {
        return slaveId;
    }

    public int getAddress ()
    {
        return address;
    }

    public int getCount ()
    {
        return count;
    }

    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;
        Command2 cmd = (Command2) obj;
        if (!cmd.name.equals (name))
            return false;
        if (!cmd.description.equals (description))
            return false;
        if (cmd.slaveId != slaveId)
            return false;
        if (cmd.address != address)
            return false;
        if (cmd.count != count)
            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 + address;
        hash = 29 * hash + count;
        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
    {
        Numeric.Value [] data = Numeric.Type.int1.createUndefArray (count);
        try
        {
            CommandDiscreteModbusModel m = new CommandDiscreteModbusModel (
                address, data);
            GeneralSettings gs = settings.getGeneral ();
            int maxPdu = gs.getMaxPdu ().getValue ();
            boolean checkCountLimits =
                gs.getCheckCountLimits ().getValue ();
            boolean strictChecking = gs.getStrictChecking ().getValue ();
            boolean allowLongMessages = gs.getAllowLongMessages ().getValue ();
            ModbusMaster master = new ModbusMaster (m, client, slaveId, maxPdu,
                checkCountLimits, strictChecking, allowLongMessages, false);
            master.readDiscreteInputs (address, count);
            actualResult = new Result (data, null,
                master.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = new Result (data, e, 0);
        }
    }

    public void save (Xml.Saver saver)
        throws IOException
    {
        saver.saveValue ("name", name);
        saver.saveValue ("description", description);
        saver.saveValue ("slaveid", slaveId);
        saver.saveValue ("address", address);
        saver.saveValue ("count", count);
        if (expectedResult != null)
        {
            saver.startTag ("result");
            saver.saveBitArrayValue ("data", expectedResult.data);
            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 address;
        private int count;
        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;
            address = 0;
            count = 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 ("address"))
            {
                return new Xml.IntegerLoader (0, 65535,
                    new Xml.Receiver<Integer> ()
                    {
                        public void receive (Integer value)
                        {
                            address = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("count"))
            {
                return new Xml.IntegerLoader (0, 65535,
                    new Xml.Receiver<Integer> ()
                    {
                        public void receive (Integer value)
                        {
                            count = 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.BitArrayLoader (
                                new Xml.Receiver<Numeric.Value []> ()
                            {
                                public void receive (Numeric.Value [] value)
                                    throws ValueException
                                {
                                    if (value.length > 65535)
                                    {
                                        throw new ValueException (
                                            "Too many values (> 65535)");
                                    }
                                    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 = Numeric.Type.int1.createUndefArray (count);
                }
                else
                {
                    if (data.length != count)
                    {
                        throw new ValueException (
                            "Number of data values does match count");
                    }
                }
                Command2 command = new Command2 (name, description, slaveId,
                    address, count, exception, data);
                receiver.receive (command);
            }
            else
            {
                Command2 command = new Command2 (name, description, slaveId,
                    address, count);
                receiver.receive (command);
            }
        }
    }
}

