
package uk.co.wingpath.modbusgui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import uk.co.wingpath.util.*;
import uk.co.wingpath.gui.*;
import uk.co.wingpath.modbus.*;
import uk.co.wingpath.event.*;
import uk.co.wingpath.event.Event;

public class Command20Panel
    implements CommandPanel
{
    private final Frontend frontend;
    private final Settings settings;
    private final ValueEventSource listeners;
    private final boolean isTester;
    private final boolean isEditor;

    private final StatusBar statusBar;
    private final GridBagPanel panel;
    private final CommandFileTableModel model;
    private final CommandValuePanel valuePanel;
    private final RadixSelector radixSelector;
    private final FileGroupPanel groupPanel;
    private final TypeSelector typeSelector;
    private final WComponent<Integer> slaveIdField;

    private Command20.Result actualResult;

    public Command20Panel (Frontend frontend, final Settings settings,
        final StatusBar statusBar, MirrorField mirror, boolean isTester, boolean isEditor)
    {
        Event.checkIsEventDispatchThread ();
        this.frontend = frontend;
        this.settings = settings;
        this.statusBar = statusBar;
        this.isTester = isTester;
        this.isEditor = isEditor;
        listeners = new ValueEventSource ();
        actualResult = null;

        panel = new GridBagPanel ();
        panel.addTitle (Command20.typeName, 3);

        GridBagPanel leftPanel = new GridBagPanel ();
        GridBagConstraints constraints = panel.createConstraints ();
        constraints.insets = new Insets (2, 0, 2, 5);
        constraints.gridwidth = 2;
        panel.add (leftPanel, constraints);

        int slaveId = settings.getGeneral ().getSlaveId ().getValue ();
        slaveIdField = new WIntegerField (statusBar, "Slave ID",
            0, 255, slaveId);
        slaveIdField.setToolTipText ("Slave identifier");
        slaveIdField.setWidthChars (4);
        slaveIdField.setMnemonic (KeyEvent.VK_I);
        slaveIdField.setMirror (mirror);
        leftPanel.addComponent (slaveIdField);

        typeSelector = TypeSelector.create (true, true);
        leftPanel.addComponent (typeSelector);

        radixSelector = new RadixSelector (true);
        radixSelector.setRadix (10);
        leftPanel.addComponent (radixSelector);

        groupPanel = new FileGroupPanel (isEditor, statusBar, mirror);
        constraints.gridx = 2;
        constraints.gridwidth = 1;
        constraints.insets = new Insets (2, 5, 2, 5);
        panel.add (groupPanel, constraints);

        model = new CommandFileTableModel (
            settings.getBigValue ().getValue (),
            groupPanel.getGroups (),
            typeSelector.getValue (),
            radixSelector.getValue (),
            isTester, isEditor, false);
        valuePanel = new CommandValuePanel ("Received Data", model,
            statusBar, mirror, 7, isEditor);
        constraints = panel.createConstraints ();
        constraints.gridwidth = 3;
        constraints.anchor = GridBagConstraints.CENTER;
        panel.add (valuePanel, constraints);

        ValueListener listener = new ValueListener ()
        {
            public void valueChanged (ValueEvent e)
            {
                Event.checkIsEventDispatchThread ();
                listeners.fireValueChanged (e);
            }
        };

        slaveIdField.addValueListener (listener);
        valuePanel.addValueListener (listener);

        groupPanel.addValueListener (new ValueListener ()
        {
            public void valueChanged (ValueEvent e)
            {
                if (!e.isChanging ())
                {
                    FileGroup [] groups = groupPanel.getGroups ();
                    model.setGroups (groups);
                    setEnabled (true, true);
                }
                listeners.fireValueChanged (e);
            }
        });

        typeSelector.addValueListener (new ValueListener ()
        {
            public void valueChanged (ValueEvent e)
            {
                if (!e.isChanging ())
                {
                    Numeric.Type type = typeSelector.getValue ();
                    model.setType (type);
                    setEnabled (true, true);
                }
                listeners.fireValueChanged (e);
            }
        });

        radixSelector.addValueListener (new ValueListener ()
        {
            public void valueChanged (ValueEvent e)
            {
                if (!e.isChanging ())
                    model.setRadix (radixSelector.getValue ());
                listeners.fireValueChanged (e);
            }
        });

        settings.getBigValue ().addValueListener (new ValueListener ()
        {
            public void valueChanged (ValueEvent e)
            {
                if (!e.isChanging ())
                {
                    BigValueFlags bvf = settings.getBigValue ().getValue ();
                    model.setBigValueFlags (bvf);
                }
                listeners.fireValueChanged (e);
            }
        });
    }

    public JPanel getPanel ()
    {
        return panel;
    }

    public String getTitle ()
    {
        return Command20.typeName;
    }

    public String getTag ()
    {
        return Command20.tag;
    }

    public String getName ()
    {
        return "20 Read File Record";
    }

    public Action getHelpAction ()
    {
        return frontend.getHelpAction ("cmd_20");
    }

    public void initialize ()
    {
    }

    @Override
    public void setEnabled (boolean enabled, boolean enExpected)
    {
        slaveIdField.setEnabled (enabled);
        typeSelector.setEnabled (enabled);
        Numeric.Type type = typeSelector.getValue ();
        if (type.isFloat () || type == Numeric.Type.int1)
        {
            radixSelector.setEnabled (false);
            radixSelector.setRadix (10);
            model.setRadix (10);
        }
        else
        {
            radixSelector.setEnabled (enabled);
        }
        groupPanel.setEnabled (enabled);
        valuePanel.setEnabled (enabled);
        if (!enabled || !enExpected)
            valuePanel.cancelEditing ();
        model.enableExpected (enExpected);
    }

    @Override
    public void highlightErrors (boolean highlight)
    {
        valuePanel.highlightErrors (highlight);
    }

    public boolean checkFields ()
    {
        assert EventQueue.isDispatchThread ();
        if (!slaveIdField.checkValue ())
            return false;
        if (!typeSelector.checkValue ())
            return false;
        if (!radixSelector.checkValue ())
            return false;
        if (!groupPanel.checkValues ())
            return false;
        if (!valuePanel.stopEditing ())
            return false;
        return true;
    }

    public void setSlaveId (int slaveId)
    {
        slaveIdField.setValue (slaveId);
    }

    public void setCommand (Command command)
    {
        if (command == null)
        {
            int slaveId = settings.getGeneral ().getSlaveId ().getValue ();
            slaveIdField.setValue (slaveId);
            final Numeric.Type type = Numeric.Type.int16;
            typeSelector.setValue (type);
            final int radix = 10;
            radixSelector.setValue (radix);
            FileGroup [] groups = new FileGroup [0];
            groupPanel.setGroups (groups);
            model.setGroups (groups);
            model.setType (type);
            model.setRadix (radix);
            setActualResult (null);
            setExpectedResult (null);
        }
        else
        {
            Command20 cmd = (Command20) command;
            slaveIdField.setValue (cmd.getSlaveId ());
            typeSelector.setValue (cmd.getType ());
            radixSelector.setValue (cmd.getRadix ());
            FileGroup [] groups = cmd.getGroups ();
            groupPanel.setGroups (groups);
            model.setGroups (groups);
            model.setType (cmd.getType ());
            model.setRadix (cmd.getRadix ());
            setActualResult (cmd.getActualResult ());
            setExpectedResult (cmd.getExpectedResult ());
        }
    }

    public void setActualResult (Command.Result result)
    {
        actualResult = (Command20.Result) result;
        if (result == null)
        {
            model.reset ();
        }
        else
        {
            model.setActualData (actualResult.getActualData ());
            ModbusException exception = actualResult.getException ();
            if (exception != null)
                statusBar.showException (exception);
        }
    }

    private void setExpectedResult (Command.Result result)
    {
        if (isTester)
        {
            valuePanel.cancelEditing ();
            if (result == null)
            {
                model.resetExpected ();
            }
            else
            {
                Command20.Result r = (Command20.Result) result;
                model.setExpectedData (r.getExpectedData ());
            }
        }
    }

    @Override
    public void expectActual ()
    {
        if (!isTester)
            return;
        model.setExpectedData (model.getActualData ());
    }

    public Command20 createCommand (String name, String description,
        ModbusException exception)
    {
        Command20 cmd;
        if (isTester)
        {
            cmd = new Command20 (name,
                description,
                slaveIdField.getValue (),
                groupPanel.getGroups (),
                typeSelector.getValue (),
                radixSelector.getValue (),
                model.getExpectedData (),
                exception);
        }
        else
        {
            cmd = new Command20 (name,
                description,
                slaveIdField.getValue (),
                groupPanel.getGroups (),
                typeSelector.getValue (),
                radixSelector.getValue ());
        }
        cmd.setActualResult (actualResult);
        return cmd;
    }

    public boolean haveValuesChanged (Command command)
    {
        boolean changed = false;
        Command20 cmd = (Command20) command;
        if (slaveIdField.hasValueChanged (cmd.getSlaveId ()))
            changed = true;
        if (groupPanel.haveValuesChanged (cmd.getGroups ()))
            changed = true;
        if (typeSelector.hasValueChanged (cmd.getType ()))
            changed = true;
        if (radixSelector.hasValueChanged (cmd.getRadix ()))
            changed = true;
        if (isTester)
        {
            Command20.Result result = cmd.getExpectedResult ();
            if (valuePanel.haveExpectedValuesChanged (
                result.getExpectedData ()))
            {
                changed = true;
            }
        }
        return changed;
    }

    public void addValueListener (ValueListener l)
    {
        listeners.addListener (l);
    }

    public void removeValueListener (ValueListener l)
    {
        listeners.removeListener (l);
    }
}


