package com.intellij.tasks.navigation;

import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.tasks.TaskManager;
import com.intellij.tasks.TaskRepository;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;

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

/**
 * @author Vladislav.Rassokhin
 */
class TaskInPsiCommentReferenceProvider extends PsiReferenceProvider {
  @NotNull
  @Override
  public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    if (!(element instanceof PsiComment)) {
      return PsiReference.EMPTY_ARRAY;
    }
    final PsiComment comment = (PsiComment) element;
    final String text = comment.getText();
    if (text== null) {
      return PsiReference.EMPTY_ARRAY;
    }
    final List<PsiCommentToTaskReference> references = new ArrayList<PsiCommentToTaskReference>();
    final TaskRepository[] repositories = TaskManager.getManager(comment.getProject()).getAllRepositories();
    for (TaskRepository repository : repositories) {
      final String id = repository.extractId(text);
      if (id != null) {
        final int i = text.indexOf(id);
        if (i >= 0) {
          references.add(new PsiCommentToTaskReference(comment, new TextRange(i, i + id.length())));
        }
      }
    }
    if (references.isEmpty()) {
      return PsiReference.EMPTY_ARRAY;
    }
    return references.toArray(new PsiReference[references.size()]);
  }
}

@@ -972,86 +972,50 @@
 ist%3C
-PsiCommentToTaskReference%3E references = new ArrayList%3CPsiCommentToTaskReferenc
+TextRange%3E ranges = new ArrayList%3CTextRang
 e%3E()
@@ -1174,24 +1174,96 @@
 sitories) %7B%0A
+      int prev = 0;%0A      String toCheck = text;%0A      while (true) %7B%0A  
       final 
@@ -1296,19 +1296,22 @@
 ractId(t
-ext
+oCheck
 );%0A     
@@ -1315,16 +1315,18 @@
     
+ 
+ 
 if (id 
-!
+=
 = nu
@@ -1339,21 +1339,42 @@
         
+ 
-final
+ break;%0A        %7D%0A       
  int i =
@@ -1375,19 +1375,22 @@
 nt i = t
-ext
+oCheck
 .indexOf
@@ -1413,10 +1413,9 @@
  (i 
-%3E=
+%3C
  0) 
@@ -1430,116 +1430,458 @@
     
+b
 re
-ferences.add(new PsiCommentToTaskReference(comment, new TextRange(i, i + id.length())));%0A        %7D%0A      %7D
+ak;%0A        %7D%0A        ranges.add(new TextRange(prev + i, prev + i + id.length()));%0A        prev += i + id.length();%0A        toCheck = text.substring(prev);%0A      %7D%0A    %7D%0A%0A    // TODO: Check intersecting ranges (between many TaskRepositories)%0A%0A    final List%3CPsiCommentToTaskReference%3E references = new ArrayList%3CPsiCommentToTaskReference%3E();%0A    for (TextRange range : ranges) %7B%0A      references.add(new PsiCommentToTaskReference(comment, range));
 %0A   

Fix multiple task id's in comment