package org.mercury_im.messenger;

import android.app.Activity;

import org.mercury_im.messenger.util.AbstractActivityLifecycleCallbacks;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Keep track of activities in "started" state.
 * This will come in handy for things like XMPPs CSI.
 *
 * @see <a href="https://medium.com/@iamsadesh/android-how-to-detect-when-app-goes-background-foreground-fd5a4d331f8a>
 *     How to detect when app goes foreground/background</a>
 */
public class ClientStateHandler extends AbstractActivityLifecycleCallbacks {

    private AtomicInteger activityReferences = new AtomicInteger(0);
    private AtomicBoolean isActivityChangingConfiguration = new AtomicBoolean(false);

    private final List<ClientStateListener> listeners = new ArrayList<>();

    @Override
    public void onActivityStarted(Activity activity) {
        if (activityReferences.incrementAndGet() == 1 && !isActivityChangingConfiguration.get()) {
            for (ClientStateListener listener : listeners) {
                listener.onClientInForeground();
            }
        }
    }

    @Override
    public void onActivityStopped(Activity activity) {
        isActivityChangingConfiguration.set(activity.isChangingConfigurations());
        if (activityReferences.decrementAndGet() == 0 && !isActivityChangingConfiguration.get()) {
            for (ClientStateListener listener : listeners) {
                listener.onClientInBackground();
            }
        }
    }

    public void addClientStateListener(ClientStateListener listener) {
        this.listeners.add(listener);
    }

    public void removeClientStateListener(ClientStateListener listener) {
        this.listeners.remove(listener);
    }
}
