package fr.adrienbrault.idea.symfony2plugin.asset;

import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import fr.adrienbrault.idea.symfony2plugin.TwigHelper;
import fr.adrienbrault.idea.symfony2plugin.asset.dic.AssetDirectoryReader;
import fr.adrienbrault.idea.symfony2plugin.asset.dic.AssetFile;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * @author Daniel Esoendiller <daniel@espendiller.net>
 */
public class AssetGoToDeclarationHandler implements GotoDeclarationHandler {

    @Nullable
    @Override
    public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int i, Editor editor) {

        // remove this call, if withName Pattern is working
        if (!isValidTag(psiElement, "stylesheets", "javascripts")) {
            return null;
        }

        List<AssetFile> assetFiles = new AssetDirectoryReader().setIncludeBundleDir(true).setProject(psiElement.getProject()).getAssetFiles();

        for(AssetFile file: assetFiles) {
            if(file.toString().equals(psiElement.getText())) {
                return new PsiElement[] { PsiManager.getInstance(psiElement.getProject()).findFile(file.getFile()) };
            }
        }

        return null;
    }

    private boolean isValidTag(PsiElement psiElement, String... tags) {
        for(String tag: tags) {
            if(TwigHelper.getAutocompletableAssetTag(tag).accepts(psiElement)) {
               return true;
            }
        }

        return false;
    }

    @Nullable
    @Override
    public String getActionText(DataContext dataContext) {
        return null;
    }
}

@@ -217,16 +217,108 @@
 Editor;%0A
+import com.intellij.patterns.ElementPattern;%0Aimport com.intellij.patterns.PlatformPatterns;%0A
 import c
@@ -619,16 +619,76 @@
 lable;%0A%0A
+import java.lang.reflect.Array;%0Aimport java.util.ArrayList;%0A
 import j
@@ -1619,32 +1619,197 @@
 ring... tags) %7B%0A
+        List%3CElementPattern%3CPsiElement%3E%3E patterns = new ArrayList%3CElementPattern%3CPsiElement%3E%3E();%0A        patterns.add(TwigHelper.getAutocompletableAssetPattern());%0A%0A
         for(Stri
@@ -1803,16 +1803,17 @@
      for
+ 
 (String 
@@ -1837,18 +1837,28 @@
         
-if
+patterns.add
 (TwigHel
@@ -1896,39 +1896,22 @@
 tag)
-.accepts(psiElement)) %7B%0A
+);%0A 
        
+%7D%0A%0A
     
@@ -1925,27 +1925,98 @@
 urn 
-true;%0A            %7D
+PlatformPatterns%0A            .or(patterns.toArray(new ElementPattern%3C?%3E%5Bpatterns.size()%5D))
 %0A   
@@ -2024,31 +2024,41 @@
     
-%7D%0A%0A
     
-    return false
+.accepts(psiElement)%0A        
 ;%0A  

Enable asset go to declaration on {{ asset() }}