
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 Command22
    implements Command<CommandResult>
{
    public static final String tag = "cmd_22";
    public static final String typeName = "22 Mask Write Holding Register";

    private final String name;
    private final String description;

    private final int slaveId;
    private final int address;
    private final Numeric.Type type;
    private final int radix;
    private final Numeric.Value orMask;
    private final Numeric.Value andMask;

    private CommandResult actualResult;
    private final CommandResult expectedResult;

    private class Model
        extends ModbusModel
    {
        Model (BigValueFlags bigValueFlags)
        {
            super (bigValueFlags, null);
        }

        @Override
        public int getValueSize (int address)
        {
            return type.getSize ();
        }

        @Override
        public boolean isSigned (int address)
            throws ModbusException
        {
            return type.isSigned ();
        }

        @Override
        public int getRadix (int address)
            throws ModbusException
        {
            return radix;
        }
    }

    Command22 (String name, String description, int slaveId, int address,
        Numeric.Type type, int radix,
        Numeric.Value orMask, Numeric.Value andMask,
        ModbusException exception)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.address = address;
        this.type = type;
        this.radix = radix;
        this.orMask = orMask;
        this.andMask = andMask;
        expectedResult = CommandResult.create (exception);
        actualResult = null;
    }

    Command22 (String name, String description, int slaveId, int address,
        Numeric.Type type, int radix,
        Numeric.Value orMask, Numeric.Value andMask)
    {
        this.name = name;
        this.description = description;
        this.slaveId = slaveId;
        this.address = address;
        this.type = type;
        this.radix = radix;
        this.orMask = orMask;
        this.andMask = andMask;
        expectedResult = null;
        actualResult = null;
    }

    public int getSlaveId ()
    {
        return slaveId;
    }

    public int getAddress ()
    {
        return address;
    }

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

    public int getRadix ()
    {
        return radix;
    }

    public Numeric.Value getOrMask ()
    {
        return orMask;
    }

    public Numeric.Value getAndMask ()
    {
        return andMask;
    }

    public CommandResult getActualResult ()
    {
        return actualResult;
    }

    public void setActualResult (CommandResult result)
    {
        actualResult = result;
    }

    public CommandResult 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;
        Command22 cmd = (Command22) 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.type != type)
            return false;
        if (cmd.radix != radix)
            return false;
        if (!cmd.orMask.equals (orMask))
            return false;
        if (!cmd.andMask.equals (andMask))
            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 + type.hashCode ();
        hash = 29 * hash + radix;
        hash = 29 * hash + orMask.hashCode ();
        hash = 29 * hash + andMask.hashCode ();
        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
        {
            BigValueFlags bigValueFlags = settings.getBigValue ().getValue ();
            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 (
                new Model (bigValueFlags),
                client, slaveId, maxPdu, checkCountLimits,
                strictChecking, allowLongMessages, false);
            master.maskWriteRegister (address,
                andMask.getLongValue (), orMask.getLongValue ());
            actualResult = CommandResult.create (master.getResponseTime ());
        }
        catch (ModbusException e)
        {
            actualResult = CommandResult.create (e);
        }
    }

    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 ("type", type.toString ());
        saver.saveValue ("radix", RadixSelector.convertRadix (radix));
        saver.saveValue ("omask", orMask, 10);
        saver.saveValue ("amask", andMask, 10);
        if (expectedResult != null)
            saver.saveValue ("result", expectedResult);
    }

    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 Numeric.Type type;
        private int radix;
        private Numeric.Value orMask;
        private Numeric.Value andMask;
        private ModbusException exception;

        XmlLoader (Xml.Receiver<Command> receiver, boolean isTester)
        {
            this.receiver = receiver;
            this.isTester = isTester;
            name = "";
            description = "";
            slaveId = 1;
            address = 0;
            type = Numeric.Type.uint16;
            radix = 10;
            orMask = null;
            andMask = 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 ("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);
                                if (type.isFloat ())
                                    throw new ValueException ("Invalid type");
                            }
                        }
                        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 ("ormask"))
            {
                return new Xml.NumericLoader (type, radix, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value value)
                            throws ValueException
                        {
                            orMask = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("omask"))
            {
                return new Xml.NumericLoader (type, 10, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value value)
                            throws ValueException
                        {
                            orMask = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("andmask"))
            {
                return new Xml.NumericLoader (type, radix, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value value)
                            throws ValueException
                        {
                            andMask = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("amask"))
            {
                return new Xml.NumericLoader (type, 10, false,
                    new Xml.Receiver<Numeric.Value> ()
                    {
                        public void receive (Numeric.Value value)
                            throws ValueException
                        {
                            andMask = value;
                        }
                    });
            }

            if (tag.equalsIgnoreCase ("result"))
            {
                return new Xml.AbstractLoader ()
                {
                    @Override
                    public Xml.Loader startChild (String tag)
                    {
                        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 (orMask == null)
                throw new ValueException ("<omask> missing");
            if (andMask == null)
                throw new ValueException ("<amask> missing");
            if (isTester)
            {
                Command22 command = new Command22 (name, description, slaveId,
                    address, type, radix, orMask, andMask, exception);
                receiver.receive (command);
            }
            else
            {
                Command22 command = new Command22 (name, description, slaveId,
                    address, type, radix, orMask, andMask);
                receiver.receive (command);
            }
        }
    }
}

