package transformation.associationtags.buttonlisteners;

import transformation.associationtags.AssociationTag;

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

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

public class ResourceListener implements ActionListener {
	
	List<AssociationTag> tags;
	Map<String, List<String>> partitionActionsMap;

	public ResourceListener(Map<String, List<String>> partitionActionsMap, List<AssociationTag> tags) {
		this.tags = tags;
		this.partitionActionsMap = partitionActionsMap;
	}
	
	/**
	 * Displays an error message, when the name of an activity partition is unchecked
	 * in the uppermost panel of the association tags view, if an action of that partition
	 * is used as a protected action in an association tag.
	 */
	public void actionPerformed(ActionEvent ae) {
		
		JCheckBox checkBox = (JCheckBox) ae.getSource();
		if (checkBox.isSelected() == false) {
            List<String> partitionActions = partitionActionsMap.get(checkBox.getText());
            if (partitionActions == null) {
                return;
            }
		    // Iterates through the association tags and sees if the selected activity partition
            // contains the protected action of that tag
			for (AssociationTag tag : tags) {
				if (partitionActions.contains(tag.getAction())) {
					checkBox.setSelected(true);
					JOptionPane.showMessageDialog(null, 
							"An action of this partition is present as a " +
							"\nprotected action in at least one of the association tags." +
							"\nRemove or change the association tag if you wish to continue.");
					return;
				}
			}
		}
		
	}
}
