/*
 * Copyright 2000-2017 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.intellij.util.indexing;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.FileTypeEvent;
import com.intellij.openapi.fileTypes.FileTypeListener;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.IntObjectMap;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * This is a light version of DirectoryIndexImpl
 *
 * @author gregsh
 */
public final class LightDirectoryIndex<T> {
  private final IntObjectMap<T> myInfoCache = ContainerUtil.createConcurrentIntObjectMap();
  private final T myDefValue;
  private final Consumer<LightDirectoryIndex<T>> myInitializer;

  public LightDirectoryIndex(@NotNull Disposable parentDisposable, @NotNull T defValue, @NotNull Consumer<LightDirectoryIndex<T>> initializer) {
    myDefValue = defValue;
    myInitializer = initializer;
    resetIndex();
    MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(parentDisposable);
    connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() {
      @Override
      public void fileTypesChanged(@NotNull FileTypeEvent event) {
        resetIndex();
      }
    });

    connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {
      @Override
      public void after(@NotNull List<? extends VFileEvent> events) {
        for (VFileEvent event : events) {
          VirtualFile file = event.getFile();
          if (file == null || file.isDirectory()) {
            resetIndex();
            break;
          }
        }
      }
    });
  }

  public void resetIndex() {
    myInfoCache.clear();
    myInitializer.consume(this);
  }

  public void putInfo(@Nullable VirtualFile file, @NotNull T value) {
    if (!(file instanceof VirtualFileWithId)) return;
    cacheInfo(file, value);
  }

  @NotNull
  public T getInfoForFile(@Nullable VirtualFile file) {
    if (!(file instanceof VirtualFileWithId)) return myDefValue;

    VirtualFile dir;
    if (!file.isDirectory()) {
      T info = getCachedInfo(file);
      if (info != null) {
        return info;
      }
      dir = file.getParent();
    }
    else {
      dir = file;
    }

    int count = 0;
    for (VirtualFile root = dir; root != null; root = root.getParent()) {
      if (++count > 1000) {
        throw new IllegalStateException("Possible loop in tree, started at " + dir.getName());
      }
      T info = getCachedInfo(root);
      if (info != null) {
        if (!dir.equals(root)) {
          cacheInfos(dir, root, info);
        }
        return info;
      }
    }

    return cacheInfos(dir, null, myDefValue);
  }

  @NotNull
  private T cacheInfos(VirtualFile dir, @Nullable VirtualFile stopAt, @NotNull T info) {
    while (dir != null) {
      cacheInfo(dir, info);
      if (dir.equals(stopAt)) {
        break;
      }
      dir = dir.getParent();
    }
    return info;
  }

  private void cacheInfo(VirtualFile file, T info) {
    myInfoCache.put(((VirtualFileWithId)file).getId(), info);
  }

  private T getCachedInfo(VirtualFile file) {
    return myInfoCache.get(((VirtualFileWithId)file).getId());
  }

}

@@ -1232,26 +1232,29 @@
 ners.Con
-tainerUtil
+currentBitSet
 ;%0Aimport
@@ -1283,28 +1283,29 @@
 tainers.
-IntObjectMap
+ContainerUtil
 ;%0Aimport
@@ -1462,16 +1462,38 @@
 il.List;
+%0Aimport java.util.Map;
 %0A%0A/**%0A *
@@ -1628,80 +1628,151 @@
 nal 
-IntObjectMap%3CT%3E myInfoCache = ContainerUtil.createConcurrentIntObjectMap
+Map%3CVirtualFile, T%3E myRootInfos = ContainerUtil.newConcurrentMap();%0A  private final ConcurrentBitSet myNonInterestingIds = new ConcurrentBitSet
 ();%0A
@@ -2832,25 +2832,58 @@
 %7B%0A    my
-InfoCache
+RootInfos.clear();%0A    myNonInterestingIds
 .clear()
@@ -3050,25 +3050,31 @@
 rn;%0A    
-cacheInfo
+myRootInfos.put
 (file, v
@@ -3188,32 +3188,51 @@
 rtualFileWithId)
+ %7C%7C !file.isValid()
 ) return myDefVa
@@ -3236,21 +3236,30 @@
 fValue;%0A
+    
 %0A    
+for (
 VirtualF
@@ -3266,437 +3266,162 @@
 ile 
-dir;%0A    if (!file.isDirectory()) %7B%0A      T info = getCachedInfo(file);%0A      if (info != null) %7B%0A        return info;%0A      %7D%0A      dir = file.getParent();%0A    %7D%0A    else %7B%0A      dir = file;%0A    %7D%0A%0A    int count = 0;%0A    for (VirtualFile root = dir; root != null; root = root.getParent()) %7B%0A      if (++count %3E 1000) %7B%0A        throw new IllegalStateException(%22Possible loop in tree, started at %22 + dir.getName());%0A  
+each = file; each != null; each = each.getParent()) %7B%0A      int id = ((VirtualFileWithId)each).getId();%0A      if (!myNonInterestingIds.get(id)) %7B%0A
     
-%7D%0A
     
-  
 T in
@@ -3429,29 +3429,33 @@
 o = 
-getCachedInfo(root
+myRootInfos.get(each
 );%0A
+  
     
@@ -3488,662 +3488,105 @@
     
-if (!dir.equals(root)) %7B%0A          cacheInfos(dir, root, info);%0A        %7D%0A        return info;%0A      %7D%0A    %7D%0A%0A    return cacheInfos(dir, null, myDefValue);%0A  %7D%0A%0A  @NotNull%0A  private T cacheInfos(VirtualFile dir, @Nullable VirtualFile stopAt, @NotNull T info) %7B%0A    while (dir != null) %7B%0A      cacheInfo(dir, info);%0A      if (dir.equals(stopAt)) %7B%0A        break;%0A      %7D%0A      dir = dir.getParent();%0A    %7D%0A    return info;%0A  %7D%0A%0A  private void cacheInfo(VirtualFile file, T info) %7B%0A    myInfoCache.put(((VirtualFileWithId)file).getId(), info);%0A  %7D%0A%0A  private T getCachedInfo(VirtualFile file) %7B%0A    return myInfoCache.get(((VirtualFileWithId)file).getId())
+  return info;%0A        %7D%0A        myNonInterestingIds.set(id);%0A      %7D%0A    %7D%0A    return myDefValue
 ;%0A  

use less memory for cache