package com.jetbrains.python.codeInsight.imports;

import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.lang.ImportOptimizer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.codeInsight.imports.PyImportOptimizer;
import org.jetbrains.annotations.NotNull;

/**
 * @author yole
 */
public class OptimizeImportsQuickFix implements LocalQuickFix {
  @NotNull
  public String getName() {
    return "Optimize imports";
  }

  @NotNull
  public String getFamilyName() {
    return "Optimize imports";
  }

  public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement element = descriptor.getPsiElement();
    if (element == null) {  // stale PSI
      return;
    }
    final PsiFile file = element.getContainingFile();
    ImportOptimizer optimizer = new PyImportOptimizer();
    final Runnable runnable = optimizer.processFile(file);
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      public void run() {
        CommandProcessor.getInstance().executeCommand(project, runnable, getFamilyName(), this);
      }
    });
  }
}

@@ -194,68 +194,8 @@
 er;%0A
-import com.intellij.openapi.application.ApplicationManager;%0A
 impo
@@ -226,32 +226,34 @@
 command.
+Write
 Command
-Processor
+Action
 ;%0Aimport
@@ -364,75 +364,8 @@
 le;%0A
-import com.jetbrains.python.codeInsight.imports.PyImportOptimizer;%0A
 impo
@@ -1035,72 +1035,68 @@
     
-ApplicationManager.getApplication().runWriteAction(new Runnab
+new WriteCommandAction.Simple(project, getFamilyName(), fi
 le
-(
 ) %7B%0A
@@ -1105,122 +1105,85 @@
     
-public void run() %7B%0A        CommandProcessor.getInstance().executeCommand(project, runnable, getFamilyName(), this
+@Override%0A      protected void run() throws Throwable %7B%0A        runnable.run(
 );%0A 
@@ -1194,16 +1194,25 @@
  %7D%0A    %7D
+.execute(
 );%0A  %7D%0A%7D

optimize imports quickfix checks out the files (PY-7195)