package org.mercury_im.messenger.core.connection;

import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smackx.csi.ClientStateIndicationManager;
import org.mercury_im.messenger.core.ClientStateListener;

import java.util.logging.Level;
import java.util.logging.Logger;

public class CsiManager implements ClientStateListener {

    private final MercuryConnectionManager connectionManager;
    private static final Logger LOGGER = Logger.getLogger(CsiManager.class.getName());

    public CsiManager(MercuryConnectionManager connectionManager) {
        this.connectionManager = connectionManager;

    }

    @Override
    public void onClientInForeground() {
        LOGGER.log(Level.INFO, "CSI: active");
        for (MercuryConnection connection : connectionManager.getConnections()) {
            tryCsiActive(connection);
        }
    }

    @Override
    public void onClientInBackground() {
        LOGGER.log(Level.INFO, "CSI: inactive");
        for (MercuryConnection connection : connectionManager.getConnections()) {
            tryCsiInactive(connection);
        }
    }

    private void tryCsiActive(MercuryConnection connection) {
        if (!connection.getConnection().isAuthenticated()) {
            return;
        }
        try {
            ClientStateIndicationManager.active(connection.getConnection());
        } catch (SmackException.NotConnectedException | InterruptedException | IllegalArgumentException e) {
            LOGGER.log(Level.WARNING, "Sending CSI state 'active' failed.", e);
        }
    }

    private void tryCsiInactive(MercuryConnection connection) {
        if (!connection.getConnection().isAuthenticated()) {
            return;
        }
        try {
            ClientStateIndicationManager.inactive(connection.getConnection());
        } catch (SmackException.NotConnectedException | InterruptedException | IllegalArgumentException e) {
            LOGGER.log(Level.WARNING, "Sending CSI state 'inactive' failed.", e);
        }
    }
}
