/*
 * Copyright 2012-2014 One Platform Foundation
 *
 * 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 org.onepf.opfpush.backoff;

import android.support.annotation.NonNull;

import org.onepf.opfutils.OPFLog;

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

/**
 * @author Kirill Rozov
 * @author Roman Savin
 * @since 05.09.14.
 */
final class InfinityExponentialBackoff implements Backoff {

    public static final int MAX_TRY_COUNT = 16;

    @NonNull
    private final AtomicInteger tryNumber = new AtomicInteger(0);

    /**
     * Compute summary delay for all tries.
     */
    @SuppressWarnings("UnusedDeclaration")
    public int summaryDelay() {
        return Integer.MAX_VALUE;
    }

    @Override
    public long getTryDelay() {
        if (tryNumber.getAndIncrement() >= MAX_TRY_COUNT) {
            return getTryDelay(tryNumber.getAndSet(0));
        }
        return getTryDelay(tryNumber.get());
    }

    private long getTryDelay(int currentTryNumber) {
        OPFLog.logMethod(currentTryNumber);
        return TimeUnit.SECONDS.toMillis(2 << currentTryNumber);
    }

    @Override
    public void reset() {
        tryNumber.set(0);
    }

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

@@ -885,16 +885,72 @@
 14.%0A */%0A
+@SuppressWarnings(%22PMD.AvoidSynchronizedAtMethodLevel%22)%0A
 final cl
@@ -1332,16 +1332,29 @@
  public 
+synchronized 
 long get
@@ -1358,32 +1358,66 @@
 getTryDelay() %7B%0A
+        int currentTryNumber = 0;%0A
         if (tryN
@@ -1412,16 +1412,17 @@
     if (
+!
 tryNumbe
@@ -1427,29 +1427,22 @@
 ber.
-getAndIncrement() %3E= 
+compareAndSet(
 MAX_
@@ -1450,16 +1450,20 @@
 RY_COUNT
+, 0)
 ) %7B%0A    
@@ -1470,35 +1470,35 @@
         
-return getTryDelay(
+currentTryNumber = 
 tryNumbe
@@ -1509,14 +1509,18 @@
 tAnd
-Set(0)
+Increment(
 );%0A 
@@ -1555,25 +1555,32 @@
 ryDelay(
-t
+currentT
 ryNumber
 .get());
@@ -1575,14 +1575,8 @@
 mber
-.get()
 );%0A 

Fix infinity exponential backoff.