package transformation.associationtags.buttonlisteners;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;

import transformation.associationtags.AssociationTag;
import transformation.associationtags.AssociationTagWindow;
import transformation.associationtags.DiagramExtension;

public class EditOKButtonListener implements ActionListener {
	
	JComboBox protectedAction;
	JTextField user;
	JComboBox role;
	DiagramExtension diagramExtension;
	AssociationTag tag;
	AssociationTagWindow window;
	List<AssociationTag> tags;
	int index;
	
	public EditOKButtonListener(JComboBox protectedAction, JTextField user, JComboBox role,
			DiagramExtension diagramExtension, AssociationTagWindow window,
			List<AssociationTag> tags, int index) {
		this.protectedAction = protectedAction;
		this.user  = user;
		this.role = role;
		this.diagramExtension = diagramExtension;
		this.window = window;
		this.tags = tags;
		this.index = index;
	}
	
	/**
	 * Saves the changes made to an association tag in the editing form.
	 * The changes are saved only in the visible list (not on the model) 
	 */
	public void actionPerformed(ActionEvent e) {
		
	    // Removes the old tag and replaces it with the edited one
		this.tags.remove(index);
		this.tag = new AssociationTag((String) protectedAction.getSelectedItem(), user.getText(), 
				(String) role.getSelectedItem());
		this.tags.add(index, this.tag);
		// Adds it to the list
		Container container = ((JButton) e.getSource()).getParent();
		while (container.getClass() != JFrame.class) {
			container = container.getParent();
		}
		// Refreshes the list
		JFrame frame = (JFrame) container;
		frame.dispose();
		window.showTags();
		
	}

}
