/*
 * Copyright 2000-2016 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.openapi.diagnostic;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.containers.FixedHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author peter
 */
public class FrequentEventDetector {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diagnostic.FrequentEventDetector");

  public enum Level {INFO, WARN, ERROR}

  private long myStartedCounting = System.currentTimeMillis();
  private final AtomicInteger myEventsPosted = new AtomicInteger();
  private final AtomicInteger myLastTraceId = new AtomicInteger();
  private final Map<String, Integer> myRecentTraces = new FixedHashMap<>(50);
  private final int myEventCountThreshold;
  private final int myTimeSpanMs;
  private final Level myLevel;
  private static final AtomicInteger disableRequests = new AtomicInteger();

  public FrequentEventDetector(int eventCountThreshold, int timeSpanMs) {
    this(eventCountThreshold, timeSpanMs, Level.INFO);
  }

  public FrequentEventDetector(int eventCountThreshold, int timeSpanMs, @NotNull Level level) {
    myEventCountThreshold = eventCountThreshold;
    myTimeSpanMs = timeSpanMs;
    myLevel = level;
  }

  /**
   * @return an error message to be logged, if the current event is a part of a "frequent"-series, null otherwise
   */
  @Nullable
  public String getMessageOnEvent(@NotNull Object event) {
    if (disableRequests.get() != 0) return null;
    if (myEventsPosted.incrementAndGet() > myEventCountThreshold) {
      boolean shouldLog = false;

      synchronized (myEventsPosted) {
        if (myEventsPosted.get() > myEventCountThreshold) {
          long timeNow = System.currentTimeMillis();
          shouldLog = timeNow - myStartedCounting < myTimeSpanMs;
          myEventsPosted.set(0);
          myStartedCounting = timeNow;
        }
      }

      if (shouldLog) {
        String trace = ExceptionUtil.getThrowableText(new Throwable());
        boolean logTrace;
        int traceId;
        synchronized (myEventsPosted) {
          Integer existingTraceId = myRecentTraces.get(trace);
          logTrace = existingTraceId == null;
          if (logTrace) {
            myRecentTraces.put(trace, traceId = myLastTraceId.incrementAndGet());
          }
          else {
            traceId = existingTraceId;
          }
        }

        return "Too many events posted, #" + traceId + ". Event: " + event + (logTrace ? "\n" + trace : "");
      }
    }
    return null;
  }

  public void logMessage(@NotNull String message) {
    if (myLevel == Level.INFO) {
      LOG.info(message);
    }
    else if (myLevel == Level.WARN) {
      LOG.warn(message);
    }
    else {
      LOG.error(message);
    }
  }

  /**
   * Logs a message if the given event is part of a "frequent" series. To just return the message without logging, use {@link #getMessageOnEvent(Object)}
   */
  public void eventHappened(@NotNull Object event) {
    String message = getMessageOnEvent(event);
    if (message != null) {
      logMessage(message);
    }
  }

  @TestOnly
  public static void disableUntil(@NotNull Disposable reenable) {
    disableRequests.incrementAndGet();
    Disposer.register(reenable, () -> disableRequests.decrementAndGet());
  }
}

@@ -2257,35 +2257,16 @@
 t() 
-!= 0) return null;%0A    if (
+== 0 && 
 myEv
@@ -2313,30 +2313,188 @@
 untThreshold
+ && manyEventsHappenedInSmallTimeSpan()) %7B%0A      return generateMessage(event);%0A    %7D%0A    return null;%0A  %7D%0A%0A  private boolean manyEventsHappenedInSmallTimeSpan(
 ) %7B%0A
-  
     boolean 
@@ -2513,26 +2513,24 @@
 false;%0A%0A    
-  
 synchronized
@@ -2545,26 +2545,24 @@
 tsPosted) %7B%0A
-  
       if (my
@@ -2603,26 +2603,24 @@
 hreshold) %7B%0A
-  
         long
@@ -2666,18 +2666,16 @@
         
-  
 shouldLo
@@ -2730,18 +2730,16 @@
         
-  
 myEvents
@@ -2753,18 +2753,16 @@
 set(0);%0A
-  
         
@@ -2790,24 +2790,28 @@
 imeNow;%0A    
+  %7D%0A
     %7D%0A      
@@ -2812,40 +2812,100 @@
     
-  %7D%0A%0A      if (shouldLog) %7B%0A    
+return shouldLog;%0A  %7D%0A%0A  @NotNull%0A  private String generateMessage(@NotNull Object event) %7B%0A
     
@@ -2964,28 +2964,24 @@
 rowable());%0A
-    
     boolean 
@@ -2990,20 +2990,16 @@
 gTrace;%0A
-    
     int 
@@ -3003,28 +3003,24 @@
 nt traceId;%0A
-    
     synchron
@@ -3049,20 +3049,16 @@
 %7B%0A      
-    
 Integer 
@@ -3108,20 +3108,16 @@
 ;%0A      
-    
 logTrace
@@ -3150,20 +3150,16 @@
 ;%0A      
-    
 if (logT
@@ -3174,20 +3174,16 @@
         
-    
 myRecent
@@ -3246,34 +3246,26 @@
 t());%0A      
-    %7D%0A    
+%7D%0A
       else %7B
@@ -3273,20 +3273,16 @@
         
-    
 traceId 
@@ -3310,29 +3310,17 @@
     
-    %7D%0A  
+%7D%0A
     
-  
 %7D%0A%0A
-    
     
@@ -3424,39 +3424,8 @@
 %22);%0A
-      %7D%0A    %7D%0A    return null;%0A
   %7D%0A

break FrequentEventDetector.getMessageOnEvent into smaller methods for JIT-friendliness