package jp.sourceforge.projects.ee2e.core.editors;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.*;
import org.eclipse.jface.text.ITextSelection;
import jp.sourceforge.projects.ee2e.core.scratch.EE2EScratchView;
import jp.sourceforge.projects.ee2e.core.EE2EPlugin;

/**
 * To change this generated comment edit the template variable "typecomment":
 * Window&gt;Preferences&gt;Java&gt;Templates.
 * To enable and disable the creation of type comments go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation.
 *
 * @author Toshikazu Ando [ ando@park.ruru.ne.jp ]
 */
public class EE2ECopyScratch implements EE2EMenuBehavior {
    public EE2ECopyScratch() {    }
    /**
    * @see jp.sourceforge.projects.ee2e.core.editors.EE2EMenuBehavior#setText()
    */
    public String getText() {
        return EE2EPlugin.getResourceString("action.copy") + "(&o)";
    }

    public static final String VIEW_TARGET = "jp.sourceforge.projects.ee2e.core.scratch.EE2EScratchView";

    /**
     * @see jp.sourceforge.projects.ee2e.core.editors.EE2EMenuBehavior#setToolTip()
     */
    public String getToolTipText() {
        return EE2EPlugin.getResourceString("action.copy.tooltip");
    }

    /**
     * @see jp.sourceforge.projects.ee2e.core.editors.EE2EMenuBehavior#doBehavior(AbstractTextEditor, IDocument, ITextSelection)
     */
    public void doBehavior(
        AbstractTextEditor editor,
        IDocument document,
        ITextSelection textSelection)
        throws BadLocationException {
        EE2EPlugin plugin = EE2EPlugin.getDefault();
        if (plugin == null) {
            return;
        }
        IWorkbench bentch = plugin.getWorkbench();
        if (bentch == null) {
            return;
        }
        IWorkbenchWindow window = bentch.getActiveWorkbenchWindow();
        if (window == null) {
            return;
        }
        IWorkbenchPage page = window.getActivePage();
        if (page == null) {
            return;
        }
        IViewPart veiwPart;
        try {
            veiwPart = page.showView(VIEW_TARGET);
        } catch (PartInitException e) {
            return;
        }
        if (!(veiwPart instanceof EE2EScratchView)) {
            return;
        }
        EE2EScratchView scratchView = (EE2EScratchView) veiwPart;
        scratchView.deleteAll();
        scratchView.append(document.get());
        int offset = textSelection.getOffset()
            + textSelection.getStartLine();
        int length = textSelection.getLength()
            - textSelection.getStartLine()
            + textSelection.getEndLine();
        scratchView.setOffset(offset,offset + length);
    }
}
