package smart_gs.drawing_tool.action;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;

import javax.swing.JTextPane;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.HTML;

import smart_gs.logical.SmartDocument;
import smart_gs.logical.TextSegment;
import sml_editor.swingui.EditorTextPane;
import smart_gs.smleditor.swingui.GSEditorTextPane;

public class RemoveMarkupAction implements ActionListener {

	private TextSegment segment;
	private EditorTextPane textPane;
	private Point point;
	
	public RemoveMarkupAction(TextSegment segment, EditorTextPane textPane,
			Point point) {
		this.segment = segment;
		this.textPane = textPane;
		this.point = point;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (segment != null) {
			SmartDocument doc = segment.getDocument();
			int id = segment.getId();
			doc.removeTextSegment(id);
		}

		JTextPane jtpMain = textPane.getTextPane();
		int selectionStart = jtpMain.getSelectionStart();
		int selectionEnd = jtpMain.getSelectionEnd();

		Element element = textPane.getElementFromPoint(point);
		SimpleAttributeSet attributeSet = new SimpleAttributeSet(element.getAttributes());
		Enumeration enumeration = attributeSet.getAttributeNames();
		while (enumeration.hasMoreElements()) {
			Object keyobj = enumeration.nextElement();
			if (keyobj instanceof HTML.Tag) {
				if (((HTML.Tag) keyobj).toString().equals(HTML.Tag.A.toString())) {
					attributeSet.removeAttribute(keyobj);
					jtpMain.setSelectionStart(element.getStartOffset());
					jtpMain.setSelectionEnd(element.getEndOffset());
					jtpMain.setCharacterAttributes(attributeSet, true);
				}
			}
		}
		jtpMain.setSelectionStart(selectionStart);
		jtpMain.setSelectionEnd(selectionEnd);
		((GSEditorTextPane) textPane).save();
	}
}
