package common.plugin.literal.popup.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.text.edits.DeleteEdit;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditor;

/**
 * テキスト化アクション
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class ToTextAction implements IEditorActionDelegate {
	/** エディタパート */
	private IEditorPart targetPart = null;

	/**
	 * @see org.eclipse.ui.IEditorActionDelegate
	 * #setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart)
	 */
	@Override
	public void setActiveEditor(final IAction action, final IEditorPart targetEditor) {
		this.targetPart = targetEditor;
	}

	/**
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(final IAction action) {
		IWorkbenchPage wbp = this.targetPart.getEditorSite().getPage();
		ITextSelection sel = (ITextSelection)wbp.getSelection();
		String str = sel.getText();
		if (str.isEmpty()) {
			return;
		}

		boolean plus = false;
		boolean dquote = false;
		MultiTextEdit mte = new MultiTextEdit();
		for (int i = 0; i < sel.getLength(); i++) {
			if (str.codePointAt(i) == '+') {
				if (!dquote) {
					plus = true;
					mte.addChild(new DeleteEdit(sel.getOffset() + i, 1));
				}
			} else if (str.codePointAt(i) == ';') {
				if (!dquote) {
					mte.addChild(new DeleteEdit(sel.getOffset() + i, 1));
				}
			} else if (str.codePointAt(i) == '\\') {
				if (i + 1 < sel.getLength()) {
					if (str.codePointAt(i + 1) == '\\' || str.codePointAt(i + 1) == '"') {
						mte.addChild(new DeleteEdit(sel.getOffset() + i, 1));
						i++;
					} else if (str.codePointAt(i + 1) == 'n') {
						mte.addChild(new DeleteEdit(sel.getOffset() + i, 2));
						i++;
					}
				}
			} else if (str.codePointAt(i) == '"') {
				mte.addChild(new DeleteEdit(sel.getOffset() + i, 1));
				dquote = !dquote;
				plus = false;
			} else if (Character.isWhitespace(str.codePointAt(i))) {
				if (plus) {
					mte.addChild(new DeleteEdit(sel.getOffset() + i, 1));
				}
			}
		}

		ITextEditor te = (ITextEditor)this.targetPart;
		IDocument doc = te.getDocumentProvider().getDocument(this.targetPart.getEditorInput());
		try {
			mte.apply(doc);
		} catch (BadLocationException ex) {
			MessageDialog.openInformation(
					this.targetPart.getEditorSite().getShell(), "", sel.getText());
		}
	}

	/**
	 * @see org.eclipse.ui.IActionDelegate
	 * #selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(final IAction action, final ISelection selection) {
		// NOP
	}
}
