package org.fluentd.logger.sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;

/**
 * Calcurate exponential delay for reconnecting
 */
public class ExponentialDelayReconnector implements Reconnector {

    private double wait = 0.5;

    private double waitIncrRate = 1.5;

    private double waitMax = 60;

    private int waitMaxCount;

    private LinkedList<Long> errorHistory;

    public ExponentialDelayReconnector() {
        waitMaxCount = getWaitMaxCount();
        errorHistory = new LinkedList<Long>();
    }

    private int getWaitMaxCount() {
        double r = waitMax / wait;
        for (int j = 1; j <= 100; j++) {
            if (r < waitIncrRate) {
                return j + 1;
            }
            r = r / waitIncrRate;
        }
        return 100;
    }

    public void addErrorHistory(long timestamp) {
        errorHistory.addLast(timestamp);
        if (errorHistory.size() > waitMaxCount) {
            errorHistory.removeFirst();
        }
    }

    public boolean isErrorHistoryEmpty() {
        return errorHistory.isEmpty();
    }

    public void clearErrorHistory() {
        errorHistory.clear();
    }

    public boolean enableReconnection(long timestamp) {
        int size = errorHistory.size();
        if (size == 0) {
            return true;
        }

        double suppressSec;
        if (size < waitMaxCount) {
            suppressSec = wait * Math.pow(waitIncrRate, size - 1);
        } else {
            suppressSec = waitMax;
        }

        return (!(timestamp - errorHistory.getLast() < suppressSec));
    }
}

@@ -33,66 +33,8 @@
 r;%0A%0A
-import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0A
 impo
@@ -209,15 +209,42 @@
 wait
- = 0.5;
+Millis = 50; // Start wait is 50ms
 %0A%0A  
@@ -311,14 +311,51 @@
 tMax
- = 60;
+Millis = 60 * 1000; // Max wait is 1 minute
 %0A%0A  
@@ -628,23 +628,35 @@
  waitMax
+Millis
  / wait
+Millis
 ;%0A      
@@ -1383,19 +1383,22 @@
 suppress
-Sec
+Millis
 ;%0A      
@@ -1446,26 +1446,35 @@
 suppress
-Sec
+Millis
  = wait
+Millis
  * Math.
@@ -1539,19 +1539,22 @@
 suppress
-Sec
+Millis
  = waitM
@@ -1555,16 +1555,22 @@
  waitMax
+Millis
 ;%0A      
@@ -1593,10 +1593,8 @@
 urn 
-(!
 (tim
@@ -1624,18 +1624,19 @@
 etLast()
- %3C
+) %3E
  suppres
@@ -1640,13 +1640,14 @@
 ress
-Sec))
+Millis
 ;%0A  

fix second/millis confusion