/*
 * Copyright 2000-2012 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 git4idea.roots;

import com.intellij.ProjectTopics;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootEvent;
import com.intellij.openapi.roots.ModuleRootListener;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsListener;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.util.messages.MessageBus;
import git4idea.GitUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.List;

/**
 * @author Kirill Likhodedov
 */
public class GitRootScanner implements BulkFileListener, ModuleRootListener, Disposable, VcsListener {

  @NotNull private final Runnable myExecuteAfterScan;
  @NotNull private final GitRootProblemNotifier myRootProblemNotifier;

  private volatile boolean myProjectIsInitialized;
  private volatile boolean myMappingsAreReady;
  private volatile boolean myScanning;
  @NotNull private final Object SCAN_LOCK = new Object();

  public GitRootScanner(@NotNull Project project, @NotNull Runnable executeAfterScan) {
    myExecuteAfterScan = executeAfterScan;

    StartupManager.getInstance(project).runWhenProjectIsInitialized(new DumbAwareRunnable() {
      @Override
      public void run() {
        myProjectIsInitialized = true;
        scanIfReady();
      }
    });

    final MessageBus messageBus = project.getMessageBus();
    messageBus.connect().subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, this);
    messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, this);
    messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, this);

    myRootProblemNotifier = GitRootProblemNotifier.getInstance(project);
  }

  @Override
  public void dispose() {
  }

  @Override
  public void before(@NotNull List<? extends VFileEvent> events) {
  }

  @Override
  public void after(@NotNull List<? extends VFileEvent> events) {
    for (VFileEvent event : events) {
      String filePath = event.getPath();
      if (filePath != null && filePath.toLowerCase().endsWith(GitUtil.DOT_GIT)) {
        scanIfReady();
      }
    }
  }

  @Override
  public void beforeRootsChange(ModuleRootEvent event) {
  }

  @Override
  public void rootsChanged(ModuleRootEvent event) {
    scanIfReady();
  }

  @Override
  public void directoryMappingChanged() {
    myMappingsAreReady = true;
    scanIfReady();
  }

  private void scanIfReady() {
    if (readyToScan()) {
      scan();
    }
  }

  private void scan() {
    if (myScanning) {
      return;
    }

    if (SwingUtilities.isEventDispatchThread()) {
      ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
          scanWithLock();
        }
      });
    }
    else {
      scanWithLock();
    }
  }

  private void scanWithLock() {
    synchronized (SCAN_LOCK) {
      if (myScanning) {
        return;
      }
      myScanning = true;
      try {
        myRootProblemNotifier.rescanAndNotifyIfNeeded();
        myExecuteAfterScan.run();
      }
      finally {
        myScanning = false;
      }
    }
  }

  private boolean readyToScan() {
    return myMappingsAreReady && myProjectIsInitialized;
  }

}

@@ -698,68 +698,8 @@
 le;%0A
-import com.intellij.openapi.application.ApplicationManager;%0A
 impo
@@ -1215,24 +1215,56 @@
 VFileEvent;%0A
+import com.intellij.util.Alarm;%0A
 import com.i
@@ -1380,39 +1380,55 @@
 java
-x.swing.*;%0Aimport java.util.Lis
+.util.List;%0Aimport java.util.concurrent.TimeUni
 t;%0A%0A
@@ -1796,102 +1796,123 @@
 dy;%0A
+%0A
   
-private volatile boolean myScanning;%0A  @NotNull private final Object SCAN_LOCK = new Object(
+@NotNull private final Alarm myAlarm;%0A  private static final long WAIT_BEFORE_SCAN = TimeUnit.SECONDS.toMillis(1
 );%0A%0A
@@ -2041,16 +2041,89 @@
 terScan;
+%0A    myRootProblemNotifier = GitRootProblemNotifier.getInstance(project);
 %0A%0A    St
@@ -2638,65 +2638,56 @@
   my
-RootProblemNotifier = GitRootProblemNotifier.getInstance(
+Alarm = new Alarm(Alarm.ThreadToUse.OWN_THREAD, 
 proj
@@ -3440,16 +3440,24 @@
       sc
+heduleSc
 an();%0A  
@@ -3479,719 +3479,426 @@
 ate 
-void scan() %7B%0A    if (myScanning) %7B%0A      return
+boolean readyToScan() %7B%0A    return myMappingsAreReady && myProjectIsInitialized
 ;%0A
-  
   %7D%0A%0A  
-  if (SwingUtilities.isEventDispatchThread()) %7B%0A      ApplicationManager.getApplication().executeOnPooledThread(new Runnable() %7B%0A        public void run() %7B%0A          scanWithLock();%0A        %7D%0A      %7D);%0A    %7D%0A    else %7B%0A      scanWithLock();%0A    %7D%0A  %7D%0A%0A  private void scanWithLock() %7B%0A    synchronized (SCAN_LOCK) %7B%0A      if (myScanning) %7B%0A        return;%0A      %7D%0A      myScanning = true;%0A      try %7B%0A        myRootProblemNotifier.rescanAndNotifyIfNeeded();%0A        myExecuteAfterScan.run();%0A      %7D%0A      finally %7B%0A        myScanning = false;%0A      %7D%0A    %7D%0A  %7D%0A%0A  private boolean readyToScan() %7B%0A    return myMappingsAreReady && myProjectIsInitialized
+private void scheduleScan() %7B%0A    myAlarm.cancelAllRequests(); // one scan is enough, no need to queue, they all do the same%0A    myAlarm.addRequest(new Runnable() %7B%0A      @Override%0A      public void run() %7B%0A        myRootProblemNotifier.rescanAndNotifyIfNeeded();%0A        myExecuteAfterScan.run();%0A      %7D%0A    %7D, WAIT_BEFORE_SCAN)
 ;%0A  

Fix blinking temporary notifications about "unregistered Git roots" IDEA-83015, IDEA-85606