package com.andresdominguez.ngsort.googrequire;

import com.google.common.collect.Iterables;
import com.intellij.lang.javascript.psi.JSExpressionStatement;
import com.intellij.lang.javascript.psi.JSLiteralExpression;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;

import java.util.ArrayList;
import java.util.Arrays;

public class GoogVarAction extends AnAction {

  @Override
  public void actionPerformed(AnActionEvent e) {
    final Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
    if (editor == null || psiFile == null) {
      return;
    }

    PsiElement currentElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
    if (currentElement == null) {
      return;
    }

    JSExpressionStatement exprStmt = PsiTreeUtil.getParentOfType(currentElement, JSExpressionStatement.class);
    if (exprStmt == null) {
      return;
    }

    final Document document = editor.getDocument();
    final int offset = exprStmt.getTextOffset();
    final String varName = getVarName(exprStmt);

    CommandProcessor.getInstance().executeCommand(getEventProject(e), new Runnable() {
      @Override
      public void run() {
        document.replaceString(offset, offset, varName);
      }
    }, "ng sort", null);
  }

  private String getVarName(JSExpressionStatement expressionStatement) {
    ArrayList<JSLiteralExpression> expressions = new ArrayList<>(
        PsiTreeUtil.findChildrenOfType(expressionStatement, JSLiteralExpression.class));
    String text = expressions.get(0).getText();
    String lastToken = Iterables.getLast(Arrays.asList(text.replaceAll("'", "").split("\\.")));
    return String.format("var %s = ", lastToken);
  }
}

@@ -57,39 +57,138 @@
 com.
-google.common.collect.Iterables
+andresdominguez.ngsort.CommandRunner;%0Aimport com.google.common.collect.Iterables;%0Aimport com.intellij.codeInsight.hint.HintManager
 ;%0Aim
@@ -536,62 +536,8 @@
 ys;%0A
-import com.intellij.openapi.command.CommandProcessor;%0A
 impo
@@ -1175,63 +1175,8 @@
 ));%0A
-    if (currentElement == null) %7B%0A      return;%0A    %7D%0A%0A
     
@@ -1302,32 +1302,114 @@
 Stmt == null) %7B%0A
+      HintManager.getInstance().showErrorHint(editor, %22Can't find goog.require%22);%0A
       return;%0A  
@@ -1579,39 +1579,18 @@
 mand
-Processor.getInstance().execute
+Runner.run
 Comm
@@ -1741,30 +1741,13 @@
   %7D%0A
+
     %7D
-, %22ng sort%22, null
 );%0A 

add error, use runCommand