package com.jetbrains.python.actions;

import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.codeInsight.template.TemplateBuilderFactory;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.ParamHelper;
import com.jetbrains.python.psi.impl.PyFunctionBuilder;
import org.jetbrains.annotations.NotNull;

import static com.jetbrains.python.psi.PyUtil.sure;

/**
 * Adds a missing top-level function to a module.
 * <br/>
 * User: dcheryasov
 * Date: Sep 15, 2010 4:34:23 PM
 * @see AddMethodQuickFix AddMethodQuickFix
 */
public class AddFunctionQuickFix  implements LocalQuickFix {

  private String myIdentifier;
  private PyFile myPyFile;

  public AddFunctionQuickFix(String identifier, PyFile module) {
    myIdentifier = identifier;
    myPyFile = module;
  }

  @NotNull
  public String getName() {
    return PyBundle.message("QFIX.NAME.add.function.$0.to.module.$1", myIdentifier, myPyFile.getName());
  }

  @NotNull
  public String getFamilyName() {
    return PyBundle.message("INSP.GROUP.python");
  }

  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
      // descriptor points to the unresolved identifier
      // there can be no name clash, else the name would have resolved, and it hasn't.
      PsiElement problem_elt = descriptor.getPsiElement().getParent(); // id -> ref expr
      String item_name = myIdentifier;
      sure(myPyFile); sure(item_name);
      sure(CodeInsightUtilBase.preparePsiElementForWrite(myPyFile));
      // try to at least match parameter count
      // TODO: get parameter style from code style
      PyFunctionBuilder builder = new PyFunctionBuilder(item_name);
      PsiElement pe = problem_elt.getParent();
      sure(pe instanceof PyCallExpression);
      PyArgumentList arglist = ((PyCallExpression)pe).getArgumentList();
      sure(arglist);
      final PyExpression[] args = arglist.getArguments();
      for (PyExpression arg : args) {
        if (arg instanceof PyKeywordArgument) { // foo(bar) -> def foo(bar_1)
          builder.parameter(((PyKeywordArgument)arg).getKeyword());
        }
        else if (arg instanceof PyReferenceExpression) {
          PyReferenceExpression refex = (PyReferenceExpression)arg;
          builder.parameter(refex.getReferencedName());
        }
        else { // use a boring name
          builder.parameter("param");
        }
      }
      PyFunction function = builder.buildFunction(project, LanguageLevel.getDefault());

      // add to the bottom
      function = (PyFunction) myPyFile.add(function);
      showTemplateBuilder(function);
    }
    catch (IncorrectOperationException ignored) {
      // we failed. tell about this
      PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.function"), MessageType.ERROR);
    }
  }

  private static void showTemplateBuilder(PyFunction method) {
    method = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(method);

    final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(method);
    ParamHelper.walkDownParamArray(
      method.getParameterList().getParameters(),
      new ParamHelper.ParamVisitor() {
        public void visitNamedParameter(PyNamedParameter param, boolean first, boolean last) {
          builder.replaceElement(param, param.getName());
        }
      }
    );

    // TODO: detect expected return type from call site context: PY-1863
    builder.replaceElement(method.getStatementList(), "return None");

    builder.run();
  }
}

@@ -2122,20 +2122,19 @@
 ;%0A      
-sure
+if 
 (pe inst
@@ -2157,24 +2157,27 @@
 ression)
-;%0A
+ %7B%0A 
       
+ 
 PyArgume
@@ -2237,24 +2237,26 @@
 st();%0A      
+  
 sure(arglist
@@ -2258,16 +2258,18 @@
 glist);%0A
+  
       fi
@@ -2324,16 +2324,18 @@
 ;%0A      
+  
 for (PyE
@@ -2354,24 +2354,26 @@
 g : args) %7B%0A
+  
         if (
@@ -2440,32 +2440,34 @@
 ar_1)%0A          
+ 
+ 
 builder.paramete
@@ -2508,34 +2508,38 @@
 ord());%0A        
-%7D%0A
+  %7D%0A  
         else if 
@@ -2589,16 +2589,18 @@
         
+ 
+ 
 PyRefere
@@ -2651,32 +2651,34 @@
 )arg;%0A          
+  
 builder.paramete
@@ -2699,32 +2699,34 @@
 erencedName());%0A
+  
         %7D%0A      
@@ -2723,24 +2723,26 @@
   %7D%0A        
+  
 else %7B // us
@@ -2757,16 +2757,18 @@
 ng name%0A
+  
         
@@ -2801,32 +2801,34 @@
 %22);%0A        
+ 
+ 
 %7D%0A      
 %7D%0A      PyFu
@@ -2811,25 +2811,71 @@
     %7D%0A      
-%7D
+  %7D%0A      %7D // else: no arglist, use empty args
 %0A      PyFun

Add Function quickfix works correctly if a function is mentioned outside a call.