package com.chrisfolger.needsmoredojo.actions;

import com.chrisfolger.needsmoredojo.base.DefineResolver;
import com.chrisfolger.needsmoredojo.refactoring.AMDImportOrganizer;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;

import java.util.ArrayList;
import java.util.List;

public class OrganizeAMDImportsAction extends AnAction
{
    @Override
    public void actionPerformed(AnActionEvent e)
    {
        final PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);

        DefineResolver resolver = new DefineResolver();
        final List<PsiElement> parameters = new ArrayList<PsiElement>();
        final List<PsiElement> defines = new ArrayList<PsiElement>();

        resolver.gatherDefineAndParameters(psiFile, defines, parameters);

        final AMDImportOrganizer organizer = new AMDImportOrganizer();

        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override
            public void run() {
                final AMDImportOrganizer.SortingResult result = organizer.sortDefinesAndParameters(defines, parameters);
                organizer.reorder(defines.toArray(new PsiElement[]{}), result.getDefines(), true, result);
                organizer.reorder(parameters.toArray(new PsiElement[]{}), result.getParameters(), false, result);
            }
        });
    }
}

@@ -386,24 +386,78 @@
 ionManager;%0A
+import com.intellij.openapi.command.CommandProcessor;%0A
 import com.i
@@ -1102,24 +1102,179 @@
 ganizer();%0A%0A
+        CommandProcessor.getInstance().executeCommand(psiFile.getProject(), new Runnable() %7B%0A            @Override%0A            public void run() %7B%0A        
         Appl
@@ -1341,32 +1341,40 @@
 ) %7B%0A            
+        
 @Override%0A      
@@ -1371,32 +1371,40 @@
 ide%0A            
+       
+ 
 public void run(
@@ -1399,32 +1399,40 @@
 ic void run() %7B%0A
+        
                 
@@ -1544,32 +1544,40 @@
                 
+        
 organizer.reorde
@@ -1659,32 +1659,40 @@
                 
+  
+      
 organizer.reorde
@@ -1785,18 +1785,16 @@
         
-%7D%0A
         
@@ -1794,16 +1794,124 @@
        %7D
+%0A                %7D);%0A            %7D%0A        %7D,%0A        %22Organize AMD Imports%22,%0A        %22Organize AMD Imports%22
 );%0A    %7D

undo works with organize amd imports