/*
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jetbrains.commandInterface.commandLine;

import com.intellij.lang.documentation.DocumentationProviderEx;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.commandInterface.command.Command;
import com.jetbrains.commandInterface.command.Help;
import com.jetbrains.commandInterface.command.Option;
import com.jetbrains.commandInterface.commandLine.psi.*;
import com.jetbrains.python.psi.PyUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.List;

/**
 * Provides quick help for arguments
 *
 * @author Ilya.Kazakevich
 */
public final class CommandLineDocumentationProvider extends DocumentationProviderEx {
  @Nullable
  @Override
  public String generateDoc(final PsiElement element, @Nullable final PsiElement originalElement) {
    Help help = findHelp(element);
    if (help == null && originalElement instanceof PsiWhiteSpace) {
      // We need to show doc for command even if cursor is right after it
      final PsiElement elementToTheLeft = originalElement.getPrevSibling();
      if (elementToTheLeft != null) {
        help = findHelp(elementToTheLeft);
      }
    }
    if (help == null) {
      return null;
    }

    final String helpText = help.getHelpString();
    // For some reason we can't return empty sting (leads to "fetching doc" string)
    return (StringUtil.isEmptyOrSpaces(helpText) ? null : helpText);
  }

  @Override
  public List<String> getUrlFor(final PsiElement element, final PsiElement originalElement) {
    final Help help = findHelp(element);
    if (help == null) {
      return null;
    }
    final String externalHelpUrl = help.getExternalHelpUrl();
    if (externalHelpUrl != null) {
      return Collections.singletonList(externalHelpUrl);
    }
    return null;
  }

  @Nullable
  @Override
  public PsiElement getCustomDocumentationElement(@NotNull final Editor editor,
                                                  @NotNull final PsiFile file,
                                                  @Nullable final PsiElement contextElement) {
    final CommandLineElement commandLineElement = PsiTreeUtil.getParentOfType(contextElement, CommandLineElement.class);
    if (commandLineElement != null) {
      return commandLineElement;
    }
    return PyUtil.as(file, CommandLineFile.class);
  }

  /**
   * Searches for help text for certain element
   * @param element element to search help for
   * @return help or
   *
   */
  @Nullable
  private static Help findHelp(@NotNull final PsiElement element) {
    if (!(element instanceof CommandLinePart)) {
      return null;
    }

    final CommandLinePart commandLinePart = (CommandLinePart)element;
    final Command realCommand = commandLinePart.findRealCommand();
    if (realCommand == null) {
      return null;
    }

    final CommandLineElement commandLineElement = PyUtil.as(element, CommandLineElement.class);
    if (commandLineElement == null) {
      return null;
    }


    final MyCommandHelpObtainer helpObtainer = new MyCommandHelpObtainer();
    commandLineElement.accept(helpObtainer);

    return helpObtainer.myResultHelp;
  }

  /**
   * Fetches text from command line part as visitor
   */
  private static final class MyCommandHelpObtainer extends CommandLineVisitor {
    private Help myResultHelp;

    @Override
    public void visitArgument(@NotNull final CommandLineArgument o) {
      super.visitArgument(o);
      myResultHelp = o.findBestHelp();
    }

    @Override
    public void visitCommand(@NotNull CommandLineCommand o) {
      super.visitCommand(o);
      final Command realCommand = o.findRealCommand();
      if (realCommand != null) {
        myResultHelp = realCommand.getHelp(false); // Arguments are ok to display here;
      }
    }

    @Override
    public void visitOption(@NotNull final CommandLineOption o) {
      super.visitOption(o);
      final Option option = o.findRealOption();
      if (option == null) {
        return;
      }
      myResultHelp = option.getHelp();
    }
  }
}
@@ -877,47 +877,8 @@
 le;%0A
-import com.intellij.psi.PsiWhiteSpace;%0A
 impo
@@ -1130,17 +1130,256 @@
 ine.psi.
-*
+CommandLineArgument;%0Aimport com.jetbrains.commandInterface.commandLine.psi.CommandLineCommand;%0Aimport com.jetbrains.commandInterface.commandLine.psi.CommandLineOption;%0Aimport com.jetbrains.commandInterface.commandLine.psi.CommandLineVisitor
 ;%0Aimport
@@ -1494,24 +1494,49 @@
 .Nullable;%0A%0A
+import java.util.Arrays;%0A
 import java.
@@ -1866,16 +1866,22 @@
 ) %7B%0A    
+final 
 Help hel
@@ -1907,321 +1907,8 @@
 t);%0A
-    if (help == null && originalElement instanceof PsiWhiteSpace) %7B%0A      // We need to show doc for command even if cursor is right after it%0A      final PsiElement elementToTheLeft = originalElement.getPrevSibling();%0A      if (elementToTheLeft != null) %7B%0A        help = findHelp(elementToTheLeft);%0A      %7D%0A    %7D%0A
     
@@ -2809,32 +2809,301 @@
 ntextElement) %7B%0A
+%0A    // First we try to find required parent for context element. Then, for element to the left of caret to support case %22command%3Ccaret%3E%22%0A    for (final PsiElement element : Arrays.asList(contextElement, file.findElementAt(editor.getCaretModel().getOffset() - 1))) %7B%0A  
     final Comman
@@ -3164,24 +3164,17 @@
 tOfType(
-contextE
+e
 lement, 
@@ -3196,32 +3196,34 @@
 ent.class);%0A    
+  
 if (commandLineE
@@ -3242,24 +3242,26 @@
 ll) %7B%0A      
+ 
+ 
 return comma
@@ -3271,24 +3271,32 @@
 ineElement;%0A
+      %7D%0A
     %7D%0A    re
@@ -3304,46 +3304,12 @@
 urn 
-PyUtil.as(file, CommandLineFile.class)
+null
 ;%0A  
@@ -3365,16 +3365,21 @@
 element%0A
+   *%0A
    * @pa
@@ -3438,21 +3438,16 @@
 help or%0A
-   *%0A
    */%0A  

Support caret on the right part of command for PY-15816