package transformation.associationtags.buttonlisteners;

import transformation.associationtags.*;

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

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

public class OKButtonListener implements ActionListener {

	JComboBox protectedAction;
	JTextField user;
	JComboBox role;
	DiagramExtension diagramExtension;
	AssociationTag tag;
	AssociationTagWindow window;
	List<AssociationTag> tags;
	List<JCheckBox> checkBoxes;
	Map<String, List<String>> partitionActionsMap;
	
	public OKButtonListener(JComboBox protectedAction, JTextField roleUser,	JComboBox roleRole, 
			DiagramExtension diagramExtension, AssociationTagWindow window,	List<AssociationTag> tags, 
			List<JCheckBox> checkBoxes, Map<String, List<String>> partitionActionsMap) {
		
		this.protectedAction = protectedAction;
		this.user  = roleUser;
		this.role = roleRole;
		this.diagramExtension = diagramExtension;
		this.window = window;
		this.tags = tags;
		this.checkBoxes = checkBoxes;
		this.partitionActionsMap = partitionActionsMap;
	}
	
	/**
	 * Validates input data on the association tag adding form 
	 * and if everything is OK, adds the association tag to the model
	 */
	public void actionPerformed(ActionEvent e) {
		
	    // Finds the activity partition to which the selected action belongs to
		for (String partition : partitionActionsMap.keySet()) {
			if (partitionActionsMap.get(partition).contains((String) protectedAction.getSelectedItem())) {
			    // Sees if the activity partition is marked as a resource
				for (JCheckBox checkBox : checkBoxes) {
					if (checkBox.getText().equals(partition) && checkBox.isSelected()) {
					    // If yes, creates a new tag and adds it to the list
					    this.tag = new AssociationTag((String) protectedAction.getSelectedItem(), user.getText(), 
				                (String) role.getSelectedItem());
						addTag(e);
						return;
					}
				}
			}
		}
		
		// If the action's activity partition was not marked as a resource, displays an error message
		JOptionPane.showMessageDialog(null, "The partition of this action" +
				"\nhas not been marked as a resource." +
				"\nTick the corresponding checkbox" +
				"\nin order to add this association tag.");
	}

	/**
	 * Adds an association tag to the visible list (but not on the model) and refreshes it
	 * 
	 * @param e    Clicking the "OK" button in the adding form
	 */
	private void addTag(ActionEvent e) {
		tags.add(tag);
		Container container = ((JButton) e.getSource()).getParent();
		while (container.getClass() != JFrame.class) {
			container = container.getParent();
		}
		JFrame frame = (JFrame) container;
		frame.dispose();
		this.window.showTags();
	}

}
