package com.contentsquare.rn.utils;

import android.os.Handler;
import android.os.Looper;

public class ExponentialBackoff {

    public interface TaskCompletionCallback {
        void onComplete(boolean success);
    }

    private final int maxRetries;
    private final double initialDelay;
    private final Task task;
    private final FailureCallback failureCallback;

    private int retries = 0;
    private double delay;

    public ExponentialBackoff(int maxRetries, double initialDelay, Task task, FailureCallback failureCallback) {
        this.maxRetries = maxRetries;
        this.initialDelay = initialDelay;
        this.task = task;
        this.failureCallback = failureCallback;
        this.delay = initialDelay;
    }

    public void start() {
        attempt();
    }

    private void attempt() {
        task.run(success -> {
            if (success) {
                System.out.println("Exponential backoff task succeeded.");
            } else {
                retries += 1;
                if (retries > maxRetries) {
                    System.out.println("Exponential backoff task failed after " + maxRetries + " retries.");
                    failureCallback.onFailure();
                } else {
                    System.out.println("Exponential backoff task failed, retrying in " + delay + " seconds...");
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        delay *= 2; // Double the delay for exponential backoff
                        attempt();
                    }, (long) (delay * 1000)); // Convert seconds to milliseconds
                }
            }
        });
    }

    public interface Task {
        void run(TaskCompletionCallback completionCallback);
    }

    public interface FailureCallback {
        void onFailure();
    }
}
