//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// Contributors:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.authoring.ui.actions;

import java.io.IOException;

import org.eclipse.epf.authoring.ui.dialogs.MethodAddLinkDialog;
import org.eclipse.epf.authoring.ui.richtext.IMethodRichText;
import org.eclipse.epf.library.util.ResourceHelper;
import org.eclipse.epf.richtext.IRichText;
import org.eclipse.epf.richtext.RichTextCommand;
import org.eclipse.epf.richtext.RichTextEditor;
import org.eclipse.epf.richtext.actions.AddLinkAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;

/**
 * Adds a link to a Rich Text editor.
 * 
 * @author Jeff Hardy
 * @author Kelvin Low
 * @since 1.0
 */
public class MethodAddLinkAction extends AddLinkAction {

	/**
	 * Creates a new instance.
	 */
	public MethodAddLinkAction() {
		super();
	}

	/**
	 * Executes the action.
	 * 
	 * @param richText
	 *            A Rich Text control.
	 */
	public void execute(IRichText richText) {
		if (richText != null) {
			if (richText instanceof IMethodRichText) {
				MethodAddLinkDialog dialog = new MethodAddLinkDialog(Display
						.getCurrent().getActiveShell(),
						(IMethodRichText) richText);
				dialog.open();
				if (dialog.getReturnCode() == Window.OK) {
					String linkURL = dialog.getLink().getURL();
					if (linkURL.length() > 0) {
						if (richText instanceof RichTextEditor) {
							((RichTextEditor) richText).addHTML(linkURL);
						} else {
							richText.executeCommand(RichTextCommand.ADD_HTML,
									linkURL);
						}
						if (dialog.getFileToCopy() != null) {
							try {
								ResourceHelper.getURLForAttachment(dialog
										.getFileToCopy(),
										((IMethodRichText) richText)
												.getMethodElement(), true);
							} catch (IOException ex) {
								ex.printStackTrace();
							}
						}
						// TODO: This will reset the RTE's modified flag to
						// false and
						// will prevent the newly added links from being saved.
						// richText.setText(richText.getText());
					}
				}
			} else {
				super.execute(richText);
			}
		}
	}

}
