package ru.adelf.idea.dotenv.indexing;

import com.intellij.psi.PsiFile;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import com.intellij.util.io.VoidDataExternalizer;
import org.jetbrains.annotations.NotNull;
import ru.adelf.idea.dotenv.util.DotEnvCallsVisitor;

import java.util.HashMap;
import java.util.Map;

public class DotEnvUsagesIndex extends FileBasedIndexExtension<String, Void> {

    public static final ID<String, Void> KEY = ID.create("ru.adelf.idea.php.dotenv.usages");
    private final KeyDescriptor<String> myKeyDescriptor = new EnumeratorStringDescriptor();

    @NotNull
    @Override
    public ID<String, Void> getName() {
        return KEY;
    }

    @NotNull
    @Override
    public DataIndexer<String, Void, FileContent> getIndexer() {
        return fileContent -> {
            final Map<String, Void> map = new HashMap<>();

            PsiFile psiFile = fileContent.getPsiFile();

            DotEnvCallsVisitor visitor = new DotEnvCallsVisitor();

            psiFile.acceptChildren(visitor);

            for(String key: visitor.getKeys()) {
                map.put(key, null);
            }

            return map;
        };
    }

    @NotNull
    @Override
    public KeyDescriptor<String> getKeyDescriptor() {
        return this.myKeyDescriptor;
    }

    @NotNull
    @Override
    public DataExternalizer<Void> getValueExternalizer() {
        return VoidDataExternalizer.INSTANCE;
    }

    @NotNull
    @Override
    public FileBasedIndex.InputFilter getInputFilter() {
        return file -> true;
    }

    @Override
    public boolean dependsOnFileContent() {
        return true;
    }

    @Override
    public int getVersion() {
        return 2;
    }
}

@@ -294,24 +294,67 @@
 ternalizer;%0A
+import com.jetbrains.php.lang.PhpFileType;%0A
 import org.j
@@ -1714,20 +1714,63 @@
 file -%3E 
-true
+file.getFileType().equals(PhpFileType.INSTANCE)
 ;%0A    %7D%0A
@@ -1919,9 +1919,9 @@
 urn 
-2
+1
 ;%0A  

Index only PHP files for usages