package transformation.associationtags.buttonlisteners;

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

import javax.swing.JCheckBox;
import javax.swing.JFrame;

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

import com.nomagic.magicdraw.core.Application;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Comment;

public class QuitListener implements ActionListener {

	Comment comment;
	List<AssociationTag> tags;
	JFrame frame;
	DiagramExtension diagramExtension;
	List<JCheckBox> checkBoxes;
	
	public QuitListener(Comment comment, List<AssociationTag> tags, JFrame frame, 
			DiagramExtension diagramExtension, List<JCheckBox> checkBoxes) {
		this.tags = tags;
		this.comment = comment;
		this.frame = frame;
		this.diagramExtension = diagramExtension;
		this.checkBoxes = checkBoxes;
		
	} 
	
	/**
	 * Saves the changes made to the association tags to the comment element
	 * and closes the association tags view.
	 */
	public void actionPerformed(ActionEvent arg0) {
		
		String text = "";
		
		// Saves the tags in the following format: 
		// <action>,<user>,<role>
		for (AssociationTag tag : tags) {
			text += tag.getAction();
			text += "," + tag.getUser();
			text += "," + tag.getRole() + "\n";
		}
		
		// Saves the names of protected resources in the following format:
		// ::<resource1>,<resource2>,...
		text += "::";
		for (JCheckBox checkBox : checkBoxes) {
			if (checkBox.isSelected()) {
				text += checkBox.getText() + ",";
			}
		}
		
		if (comment == null) {
			comment = this.diagramExtension.addTagComment(tags);
		}
		this.comment.setBody(text);
		
		// Closes the association tags view
		this.frame.dispose();
		// Makes the project saveable
		Application.getInstance().getProject().setDirty(true);	
	}

}
