
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 Command20
    implements Command<Command20.Result>
{
    public static final String tag = "cmd_20";
    public static final String typeName = "20 Read File Record";

    private final String name;
    private final String description;

    private final int slaveId;
    private final FileGroup [] groups;
    private final Numeric.Type type;
    private final int radix;

    private Result actualResult;
    private final Result expectedResult;

    public class Result
        implements Command.Result
    {
        private final Numeric.PatVal [] data;
        private final ModbusException exception;
        private final long responseTime;
 
        Result (Numeric.PatVal [] data, ModbusException exception,
            long responseTime)
        {
            int nvalues = FileGroup.countValues (groups);
            if (data.length != nvalues)
            {
                throw new IllegalArgumentException ("data wrong length: " +
                    data.length + " instead of " + nvalues);
            }
            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 (Numeric.Value []) data.clone ();
        }

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

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

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

    Command20 (String name, String description, int slaveId,
        FileGroup [] groups, Numeric.Type type, int radix,
        Numeric.Pattern [] data, ModbusException exception)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        if (groups == null)
            throw new NullPointerException ();
        this.groups = groups;
        this.type = type;
        this.radix = radix;
        expectedResult = new Result (data, exception, 0);
        actualResult = null;
    }

    Command20 (String name, String description, int slaveId,
        FileGroup [] groups, Numeric.Type type, int radix)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.groups = groups;
        if (groups == null)
            throw new NullPointerException ();
        this.type = type;
        this.radix = radix;
        expectedResult = null;
        actualResult = null;
    }

    public int getSlaveId ()
    {
        return slaveId;
    }

    public FileGroup [] getGroups ()
    {
        return groups;
    }

    public Numeric.Type getType ()
    {
        return type;
    }

    public int getRadix ()
    {
        return radix;
    }

    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;
        Command20 cmd = (Command20) obj;
        if (!cmd.name.equals (name))
            return false;
        if (!cmd.description.equals (description))
            return false;
        if (cmd.slaveId != slaveId)
            return false;
        if (!Arrays.equals (cmd.groups, groups))
            return false;
        if (cmd.type != type)
            return false;
        if (cmd.radix != radix)
            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;
        for (FileGroup group : groups)
            hash = 29 * hash + group.hashCode ();
        hash = 29 * hash + type.hashCode ();
        hash = 29 * hash + radix;
        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
    {
        BigValueFlags bigValueFlags = settings.getBigValue ().getValue ();
        FileRegisterModel model = new FileRegisterModel (bigValueFlags,
            type, radix, groups);
        try
        {
            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 (null, client, slaveId,
                maxPdu, checkCountLimits, strictChecking, allowLongMessages,
                false);
            ModbusFilePacker filePacker = new ModbusFilePacker (model);
            master.setModbusFilePacker (filePacker);
            master.readFileRecord (groups);
            actualResult = new Result (model.getData (), null,
                master.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = new Result (model.getData (), e, 0);
        }
    }

    public void save (Xml.Saver saver)
        throws IOException
    {
        saver.saveValue ("name", name);
        saver.saveValue ("description", description);
        saver.saveValue ("slaveid", slaveId);
        saver.saveValue ("type", type.toString ());
        saver.saveValue ("radix", RadixSelector.convertRadix (radix));
        saver.startTag ("groups");
        FileGroupXml.save (saver, groups);
        saver.endTag ("groups");
        if (expectedResult != null)
        {
            saver.startTag ("result");
            saver.saveValue ("pdata",
                (Numeric.Pattern []) expectedResult.data, 10);
            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 FileGroup [] groups;
        private Numeric.Type type;
        private int radix;
        private boolean compareData;
        private Numeric.Pattern [] data;
        private ModbusException exception;

        XmlLoader (Xml.Receiver<Command> receiver, boolean isTester)
        {
            this.receiver = receiver;
            this.isTester = isTester;
            name = "";
            description = "";
            slaveId = 1;
            groups = null;
            type = Numeric.Type.int16;
            radix = 10;
            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 ("groups"))
            {
                return FileGroupXml.getXmlLoader (
                    new Xml.Receiver<FileGroup []> ()
                    {
                        public void receive (FileGroup [] value)
                        {
                            groups = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("type"))
            {
                return new Xml.StringLoader (new Xml.Receiver<String> ()
                {
                    public void receive (String value)
                        throws ValueException
                    {
                        try
                        {
                            if (value.equals ("discrete"))
                                type = Numeric.Type.int1;
                            else
                                type = Numeric.Type.valueOf (value);
                        }
                        catch (IllegalArgumentException e)
                        {
                            throw new ValueException (e.getMessage ());
                        }
                    }
                });
            }

            if (tag.equalsIgnoreCase ("radix"))
            {
                return new Xml.StringLoader (new Xml.Receiver<String> ()
                {
                    public void receive (String value)
                        throws ValueException
                    {
                        if (!value.equals ("10"))
                        {
                            if (value.equals ("10U"))
                                value = "10";
                            type = type.unsigned ();
                        }
                        radix = RadixSelector.convertRadix (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 ("pdata"))
                        {
                            return new Xml.NumericPatternArrayLoader (type, 10,
                                new Xml.Receiver<Numeric.Pattern []> ()
                            {
                                public void receive (Numeric.Pattern [] value)
                                    throws ValueException
                                {
                                    if (value.length > 65535)
                                    {
                                        throw new ValueException (
                                            "Too many values (> 65535)");
                                    }
                                    data = value;
                                }
                            });
                        }

                        if (tag.equalsIgnoreCase ("data"))
                        {
                            return new Xml.NumericArrayLoader (type, 10, 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)");
                                    }
                                    data = Numeric.createPatternArray (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 (groups == null)
                throw new ValueException ("<groups> missing");
            if (isTester)
            {
                int nvalues = FileGroup.countValues (groups);
                if (data == null || exception != null || !compareData)
                    data = type.createEmptyPatternArray (nvalues);
                else if (data.length != nvalues)
                    throw new ValueException ("Wrong number of values");
                Command20 command = new Command20 (name, description, slaveId,
                    groups, type, radix, data, exception);
                receiver.receive (command);
            }
            else
            {
                Command20 command = new Command20 (name, description, slaveId,
                    groups, type, radix);
                receiver.receive (command);
            }
        }
    }
}

