package neptulon.client;

import java.util.logging.Logger;

import neptulon.client.callbacks.ConnCallback;

// todo: needs review

/**
 * This class extends {ConnImpl} with auto-reconnect functionality.
 */
public class ReconnImpl extends ConnImpl {
    private static final Logger logger = Logger.getLogger("Titan: " + ReconnImpl.class.getSimpleName());
    private boolean firstConnection = true;
    private boolean manuallyDisconnected = false;
    private boolean retriesExhausted = false;
    private final int retryLimit = 5;
    private int retryCount = 0;

    @Override
    public synchronized void connect(final ConnCallback cb) {
        super.connect(new ConnCallback() {
            @Override
            public void connected() {
                // only fire connected event once
                if (firstConnection) {
                    cb.connected();
                }
                firstConnection = false;
            }

            @Override
            public void disconnected(String reason) {
                // only fire disconnected event when retries are exhausted or on manual disconnect call
                if (manuallyDisconnected || retriesExhausted) {
                    cb.disconnected(reason);
                    return;
                }

                // try to reconnect
                if (retryCount <= retryLimit) {
                    // todo: do this in a background thread with exponential backoff
                    connect(this);
                }

                retryCount++;
            }
        });
    }

    @Override
    public synchronized void close() {
        manuallyDisconnected = true;
        super.close();
    }
}

@@ -19,16 +19,40 @@
 lient;%0A%0A
+import java.util.Timer;%0A
 import j
@@ -534,27 +534,121 @@
 nal 
-int retryLimit = 5;
+Timer timer = new Timer();%0A    private final int retryLimit = 7;%0A    private final int retryDelay = 5; // seconds
 %0A   
@@ -1471,32 +1471,113 @@
 tryLimit) %7B%0A    
+                connect(this);%0A                %7D%0A%0A                retryCount++;%0A%0A
                 
@@ -1641,16 +1641,18 @@
 backoff%0A
+//
         
@@ -1667,70 +1667,243 @@
     
-connect(this);%0A                %7D%0A%0A                retryCount++
+timer.schedule(new TimerTask() %7B%0A//                        @Override%0A//                        public void run() %7B%0A//                            // Your database code here%0A//                        %7D%0A//                    %7D, 2*60*1000)
 ;%0A  

add exponential backoff reconnect stub