/*
 * Copyright 2016 Timothy Brooks
 *
 * 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 net.uncontended.precipice.rate;

import net.uncontended.precipice.BackPressure;
import net.uncontended.precipice.Failable;
import net.uncontended.precipice.metrics.CountMetrics;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class RateLimiter<Rejected extends Enum<Rejected>> implements BackPressure<Rejected> {

    private final Rejected rejectedReason;
    private final long allowedPerPeriod;
    private final AtomicLong count = new AtomicLong(0);
    private final AtomicLong rolloverTime;
    private final long nanoDuration;

    public RateLimiter(Rejected rejectedReason, long allowedPerPeriod, long duration, TimeUnit timeUnit) {
        this.rejectedReason = rejectedReason;
        this.allowedPerPeriod = allowedPerPeriod;
        this.nanoDuration = timeUnit.toNanos(duration);
        this.rolloverTime = new AtomicLong(System.nanoTime() + nanoDuration);
    }

    @Override
    public Rejected acquirePermit(long number, long nanoTime) {
        for (; ; ) {
            long currentCount = count.incrementAndGet();
            if (currentCount > allowedPerPeriod) {
                long localRolloverTime = rolloverTime.get();
                if (localRolloverTime > nanoTime) {
                    return rejectedReason;
                } else if (count.compareAndSet(currentCount, 0) &&
                        rolloverTime.compareAndSet(localRolloverTime, nanoTime + nanoDuration)) {
                    return null;
                }
            } else {
                return null;
            }
        }
    }

    @Override
    public void releasePermit(long number, long nanoTime) {
    }

    @Override
    public void releasePermit(long number, Failable result, long nanoTime) {
    }

    @Override
    public <Result extends Enum<Result> & Failable> void registerResultMetrics(CountMetrics<Result> metrics) {

    }
}

@@ -1594,32 +1594,63 @@
 ong nanoTime) %7B%0A
+        adjustTime(nanoTime);%0A%0A
         for (; ;
@@ -1696,25 +1696,69 @@
 unt.
-incrementAndGet()
+get();%0A            long proposedCount = currentCount + number
 ;%0A  
@@ -1771,23 +1771,24 @@
     if (
-current
+proposed
 Count %3E 
@@ -1827,109 +1827,106 @@
     
-long localRolloverTime = rolloverTime.get();%0A                if (localRolloverTime %3E nanoTime) %7B%0A    
+return rejectedReason;%0A            %7D else if (count.compareAndSet(currentCount, proposedCount)) %7B%0A
     
@@ -1940,38 +1940,28 @@
      return 
-rejectedReason
+null
 ;%0A          
@@ -1963,116 +1963,168 @@
     
+   %7D%0A
        
-%7D else if (count.compareAndSet(currentCount, 0) &&%0A                        rolloverTime.compareAndSet
+ %7D%0A    %7D%0A%0A    private void adjustTime(long nanoTime) %7B%0A        for (; ; ) %7B%0A            long localRolloverTime = rolloverTime.get();%0A            if 
 (loc
@@ -2137,17 +2137,18 @@
 overTime
-,
+ %3E
  nanoTim
@@ -2152,32 +2152,12 @@
 Time
- + nanoDuration)) %7B%0A    
+) %7B%0A
     
@@ -2166,37 +2166,32 @@
           return
- null
 ;%0A              
@@ -2192,32 +2192,90 @@
     
-    %7D%0A            %7D else
+%7D else if (rolloverTime.compareAndSet(localRolloverTime, nanoTime + nanoDuration))
  %7B%0A 
@@ -2285,35 +2285,36 @@
             
-return null
+count.set(0)
 ;%0A          

Fix a few issues with basic rate limiter