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();
      if (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");
          }
        }
      } // else: no arglist, use empty args
      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();
  }
}

@@ -312,16 +312,55 @@
 riptor;%0A
+import com.intellij.facet.FacetFinder;%0A
 import c
@@ -396,16 +396,16 @@
 roject;%0A
-
 import c
@@ -476,16 +476,49 @@
 lement;%0A
+import com.intellij.psi.PsiFile;%0A
 import c
@@ -563,16 +563,63 @@
 eption;%0A
+import com.jetbrains.django.facet.DjangoFacet;%0A
 import c
@@ -2206,17 +2206,29 @@
 lement p
-e
+roblem_parent
  = probl
@@ -2258,17 +2258,29 @@
    if (p
-e
+roblem_parent
  instanc
@@ -2356,17 +2356,29 @@
 ession)p
-e
+roblem_parent
 ).getArg
@@ -2981,16 +2981,347 @@
 %0A      %7D
+%0A      else if (problem_parent != null) %7B%0A        PsiFile source_file = problem_parent.getContainingFile();%0A        if (source_file != null && %22urls.py%22.equals(source_file.getName()) && DjangoFacet.isPresent(source_file)) %7B%0A          builder.parameter(%22request%22); // specifically for mentions in urlpatterns%0A        %7D%0A      %7D%0A     
  // else
@@ -3426,19 +3426,41 @@
 vel.
-getDefault(
+forFile(myPyFile.getVirtualFile()
 ));%0A

Add Function quickfix works correctly if a function is mentioned outside a call. Special handling of Django's urls.py