package de.renew.layoutwindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;

import de.renew.draw.ui.api.CommandApi;
import de.renew.draw.ui.ontology.AbstractCommand;
import de.renew.draw.ui.ontology.Alignment;
import de.renew.draw.ui.ontology.Anchor;

/**
 * An ActionListener that executes a specific AlignCommand based on the
 * current selection of a JComboBox (Swing).
 */
public class AlignCommandActionListener implements ActionListener {
    private final AbstractCommand[] _commands;
    private final JComboBox _combobox;

    /**
     * Constructor of the class AlignCommandActionListener.
     *
     * @param name the base name for each generated alignment command
     * @param op the operation code specifying the alignment type
     * @param combobox the JComboBox whose items determine the available commands
     */
    public AlignCommandActionListener(String name, Alignment op, JComboBox<String> combobox) {
        this._combobox = combobox;
        int n = combobox.getItemCount();

        this._commands = new AbstractCommand[n];
        Anchor[] anchors = Anchor.values();
        for (int i = 0; i < n; i++) {
            Object item = combobox.getItemAt(i);
            this._commands[i] = CommandApi.createAlignCommand(name + " " + item, op, anchors[i]);
        }
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        int selectedIndex = _combobox.getSelectedIndex();
        this._commands[selectedIndex].execute();
    }
}