package org.eclipse.paho.mqttv5.client.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.paho.mqttv5.client.IMqttMessageListener;
import org.eclipse.paho.mqttv5.client.MqttActionListener;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.client.MqttToken;
import org.eclipse.paho.mqttv5.client.logging.Logger;
import org.eclipse.paho.mqttv5.client.logging.LoggerFactory;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttAuth;
import org.eclipse.paho.mqttv5.common.packet.MqttDisconnect;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.eclipse.paho.mqttv5.common.packet.MqttPubAck;
import org.eclipse.paho.mqttv5.common.packet.MqttPubComp;
import org.eclipse.paho.mqttv5.common.packet.MqttPublish;
import org.eclipse.paho.mqttv5.common.util.MqttTopicValidator;

/* JADX INFO: loaded from: classes2.dex */
public class CommsCallback implements Runnable {
    private static final String CLASS_NAME = "org.eclipse.paho.mqttv5.client.internal.CommsCallback";
    private static final int INBOUND_QUEUE_SIZE = 10;
    private Future<?> callbackFuture;
    private Thread callbackThread;
    private ClientComms clientComms;
    private ClientState clientState;
    private MqttCallback mqttCallback;
    private MqttCallback reconnectInternalCallback;
    private String threadName;
    private Logger log = LoggerFactory.getLogger(LoggerFactory.MQTT_CLIENT_MSG_CAT, CLASS_NAME);
    private AtomicInteger messageHandlerId = new AtomicInteger(0);
    private State current_state = State.STOPPED;
    private State target_state = State.STOPPED;
    private final Object lifecycle = new Object();
    private final Object workAvailable = new Object();
    private final Object spaceAvailable = new Object();
    private boolean manualAcks = false;
    private ArrayList<MqttPublish> messageQueue = new ArrayList<>(10);
    private ArrayList<MqttToken> completeQueue = new ArrayList<>(10);
    private HashMap<Integer, IMqttMessageListener> callbackMap = new HashMap<>();
    private HashMap<String, Integer> callbackTopicMap = new HashMap<>();
    private HashMap<Integer, Integer> subscriptionIdMap = new HashMap<>();

    private enum State {
        STOPPED,
        RUNNING,
        QUIESCING;

        /* JADX INFO: renamed from: values, reason: to resolve conflict with enum method */
        public static State[] valuesCustom() {
            State[] stateArrValuesCustom = values();
            int length = stateArrValuesCustom.length;
            State[] stateArr = new State[length];
            System.arraycopy(stateArrValuesCustom, 0, stateArr, 0, length);
            return stateArr;
        }
    }

    CommsCallback(ClientComms clientComms) {
        this.clientComms = clientComms;
        this.log.setResourceName(clientComms.getClient().getClientId());
    }

    public void setClientState(ClientState clientState) {
        this.clientState = clientState;
    }

    public void start(String str, ExecutorService executorService) {
        this.threadName = str;
        synchronized (this.lifecycle) {
            if (this.current_state == State.STOPPED) {
                synchronized (this.workAvailable) {
                    this.messageQueue.clear();
                    this.completeQueue.clear();
                }
                this.target_state = State.RUNNING;
                if (executorService == null) {
                    new Thread(this).start();
                } else {
                    this.callbackFuture = executorService.submit(this);
                }
            }
        }
        while (!isRunning()) {
            try {
                Thread.sleep(100L);
            } catch (Exception unused) {
            }
        }
    }

    public void stop() {
        synchronized (this.lifecycle) {
            Future<?> future = this.callbackFuture;
            if (future != null) {
                future.cancel(true);
            }
        }
        if (isRunning()) {
            Logger logger = this.log;
            String str = CLASS_NAME;
            logger.fine(str, "stop", "700");
            synchronized (this.lifecycle) {
                this.target_state = State.STOPPED;
            }
            if (!Thread.currentThread().equals(this.callbackThread)) {
                synchronized (this.workAvailable) {
                    this.log.fine(str, "stop", "701");
                    this.workAvailable.notifyAll();
                }
                while (isRunning()) {
                    try {
                        Thread.sleep(100L);
                    } catch (Exception unused) {
                    }
                    this.clientState.notifyQueueLock();
                }
            }
            this.callbackThread = null;
            this.log.fine(CLASS_NAME, "stop", "703");
        }
    }

    public void setCallback(MqttCallback mqttCallback) {
        this.mqttCallback = mqttCallback;
    }

    public void setReconnectCallback(MqttCallback mqttCallback) {
        this.reconnectInternalCallback = mqttCallback;
    }

    public void setManualAcks(boolean z) {
        this.manualAcks = z;
    }

    @Override // java.lang.Runnable
    public void run() {
        MqttToken mqttToken;
        MqttPublish mqttPublish;
        Thread threadCurrentThread = Thread.currentThread();
        this.callbackThread = threadCurrentThread;
        threadCurrentThread.setName(this.threadName);
        synchronized (this.lifecycle) {
            this.current_state = State.RUNNING;
        }
        while (isRunning()) {
            try {
                try {
                    synchronized (this.workAvailable) {
                        if (isRunning() && this.messageQueue.isEmpty() && this.completeQueue.isEmpty()) {
                            this.log.fine(CLASS_NAME, "run", "704");
                            this.workAvailable.wait();
                        }
                    }
                } catch (Throwable th) {
                    try {
                        Logger logger = this.log;
                        String str = CLASS_NAME;
                        logger.fine(str, "run", "714", null, th);
                        this.clientComms.shutdownConnection(null, new MqttException(th), null);
                        synchronized (this.spaceAvailable) {
                            this.log.fine(str, "run", "706");
                            this.spaceAvailable.notifyAll();
                        }
                    } catch (Throwable th2) {
                        synchronized (this.spaceAvailable) {
                            this.log.fine(CLASS_NAME, "run", "706");
                            this.spaceAvailable.notifyAll();
                            throw th2;
                        }
                    }
                }
            } catch (InterruptedException unused) {
            }
            if (isRunning()) {
                synchronized (this.workAvailable) {
                    if (this.completeQueue.isEmpty()) {
                        mqttToken = null;
                    } else {
                        mqttToken = this.completeQueue.get(0);
                        this.completeQueue.remove(0);
                    }
                }
                if (mqttToken != null) {
                    handleActionComplete(mqttToken);
                }
                synchronized (this.workAvailable) {
                    if (this.messageQueue.isEmpty()) {
                        mqttPublish = null;
                    } else {
                        mqttPublish = this.messageQueue.get(0);
                        this.messageQueue.remove(0);
                    }
                }
                if (mqttPublish != null) {
                    handleMessage(mqttPublish);
                }
            }
            if (isQuiescing()) {
                this.clientState.checkQuiesceLock();
            }
            synchronized (this.spaceAvailable) {
                this.log.fine(CLASS_NAME, "run", "706");
                this.spaceAvailable.notifyAll();
            }
        }
        synchronized (this.lifecycle) {
            this.current_state = State.STOPPED;
        }
        this.callbackThread = null;
    }

    private void handleActionComplete(MqttToken mqttToken) throws MqttException {
        synchronized (mqttToken) {
            this.log.fine(CLASS_NAME, "handleActionComplete", "705", new Object[]{mqttToken.internalTok.getKey()});
            if (mqttToken.isComplete()) {
                this.clientState.notifyComplete(mqttToken);
            }
            mqttToken.internalTok.notifyComplete();
            if (!mqttToken.internalTok.isNotified()) {
                if (this.mqttCallback != null && mqttToken.internalTok.isDeliveryToken() && mqttToken.isComplete()) {
                    try {
                        this.mqttCallback.deliveryComplete(mqttToken);
                    } catch (Throwable th) {
                        this.log.fine(CLASS_NAME, "handleActionComplete", "726", new Object[]{th});
                    }
                }
                fireActionEvent(mqttToken);
                if (mqttToken.isComplete()) {
                    mqttToken.internalTok.setNotified(true);
                }
            } else if (mqttToken.isComplete() && (mqttToken.internalTok.isDeliveryToken() || (mqttToken.getActionCallback() instanceof MqttActionListener))) {
                mqttToken.internalTok.setNotified(true);
            }
        }
    }

    public void connectionLost(MqttException mqttException, MqttDisconnect mqttDisconnect) {
        try {
            MqttCallback mqttCallback = this.mqttCallback;
            if (mqttCallback != null && mqttDisconnect != null) {
                this.log.fine(CLASS_NAME, "connectionLost", "722", new Object[]{mqttDisconnect.toString()});
                this.mqttCallback.disconnected(new MqttDisconnectResponse(mqttDisconnect.getReturnCode(), mqttDisconnect.getProperties().getReasonString(), (ArrayList) mqttDisconnect.getProperties().getUserProperties(), mqttDisconnect.getProperties().getServerReference()));
            } else if (mqttCallback != null && mqttException != null) {
                this.log.fine(CLASS_NAME, "connectionLost", "708", new Object[]{mqttException});
                this.mqttCallback.disconnected(new MqttDisconnectResponse(mqttException));
            }
            if (this.reconnectInternalCallback == null || mqttException == null) {
                return;
            }
            this.reconnectInternalCallback.disconnected(new MqttDisconnectResponse(mqttException));
        } catch (Throwable th) {
            this.log.fine(CLASS_NAME, "connectionLost", "720", new Object[]{th});
        }
    }

    public void fireActionEvent(MqttToken mqttToken) {
        MqttActionListener actionCallback;
        if (mqttToken == null || (actionCallback = mqttToken.getActionCallback()) == null) {
            return;
        }
        if (mqttToken.getException() == null) {
            this.log.fine(CLASS_NAME, "fireActionEvent", "716", new Object[]{mqttToken.internalTok.getKey()});
            actionCallback.onSuccess(mqttToken);
        } else {
            this.log.fine(CLASS_NAME, "fireActionEvent", "716", new Object[]{mqttToken.internalTok.getKey()});
            actionCallback.onFailure(mqttToken, mqttToken.getException());
        }
    }

    public void messageArrived(MqttPublish mqttPublish) {
        if (this.mqttCallback != null || this.callbackMap.size() > 0) {
            synchronized (this.spaceAvailable) {
                while (isRunning() && !isQuiescing() && this.messageQueue.size() >= 10) {
                    try {
                        this.log.fine(CLASS_NAME, "messageArrived", "709");
                        this.spaceAvailable.wait(200L);
                    } catch (InterruptedException unused) {
                    }
                }
            }
            if (isQuiescing()) {
                return;
            }
            synchronized (this.workAvailable) {
                this.messageQueue.add(mqttPublish);
                this.log.fine(CLASS_NAME, "messageArrived", "710");
                this.workAvailable.notifyAll();
            }
        }
    }

    public void authMessageReceived(MqttAuth mqttAuth) {
        MqttCallback mqttCallback = this.mqttCallback;
        if (mqttCallback != null) {
            try {
                mqttCallback.authPacketArrived(mqttAuth.getReturnCode(), mqttAuth.getProperties());
            } catch (Throwable th) {
                this.log.fine(CLASS_NAME, "authMessageReceived", "727", new Object[]{th});
            }
        }
    }

    public void mqttErrorOccurred(MqttException mqttException) {
        this.log.warning(CLASS_NAME, "mqttErrorOccurred", "721", new Object[]{mqttException.getMessage()});
        MqttCallback mqttCallback = this.mqttCallback;
        if (mqttCallback != null) {
            try {
                mqttCallback.mqttErrorOccurred(mqttException);
            } catch (Exception e) {
                this.log.fine(CLASS_NAME, "mqttErrorOccurred", "724", new Object[]{e});
            }
        }
    }

    public void quiesce() {
        synchronized (this.lifecycle) {
            if (this.current_state == State.RUNNING) {
                this.current_state = State.QUIESCING;
            }
        }
        synchronized (this.spaceAvailable) {
            this.log.fine(CLASS_NAME, "quiesce", "711");
            this.spaceAvailable.notifyAll();
        }
    }

    boolean areQueuesEmpty() {
        boolean z;
        synchronized (this.workAvailable) {
            z = this.completeQueue.isEmpty() && this.messageQueue.isEmpty();
        }
        return z;
    }

    public boolean isQuiesced() {
        return isQuiescing() && areQueuesEmpty();
    }

    private void handleMessage(MqttPublish mqttPublish) throws Exception {
        String topicName = mqttPublish.getTopicName();
        this.log.fine(CLASS_NAME, "handleMessage", "713", new Object[]{Integer.valueOf(mqttPublish.getMessageId()), topicName});
        deliverMessage(topicName, mqttPublish.getMessageId(), mqttPublish.getMessage());
        if (this.manualAcks || mqttPublish.getMessage().getQos() != 1) {
            return;
        }
        this.clientComms.internalSend(new MqttPubAck(0, mqttPublish.getMessageId(), new MqttProperties()), new MqttToken(this.clientComms.getClient().getClientId()));
    }

    public void messageArrivedComplete(int i, int i2) throws MqttException {
        if (i2 == 1) {
            this.clientComms.internalSend(new MqttPubAck(0, i, new MqttProperties()), new MqttToken(this.clientComms.getClient().getClientId()));
        } else if (i2 == 2) {
            this.clientComms.deliveryComplete(i);
            MqttPubComp mqttPubComp = new MqttPubComp(0, i, new MqttProperties());
            this.log.info(CLASS_NAME, "messageArrivedComplete", "723", new Object[]{mqttPubComp.toString()});
            this.clientComms.internalSend(mqttPubComp, new MqttToken(this.clientComms.getClient().getClientId()));
        }
    }

    public void asyncOperationComplete(MqttToken mqttToken) {
        if (isRunning()) {
            synchronized (this.workAvailable) {
                this.completeQueue.add(mqttToken);
                this.log.fine(CLASS_NAME, "asyncOperationComplete", "715", new Object[]{mqttToken.internalTok.getKey()});
                this.workAvailable.notifyAll();
            }
            return;
        }
        try {
            handleActionComplete(mqttToken);
        } catch (MqttException e) {
            this.log.fine(CLASS_NAME, "asyncOperationComplete", "719", null, e);
            this.clientComms.shutdownConnection(null, new MqttException(e), null);
        }
    }

    protected Thread getThread() {
        return this.callbackThread;
    }

    public void setMessageListener(Integer num, String str, IMqttMessageListener iMqttMessageListener) {
        int iIncrementAndGet = this.messageHandlerId.incrementAndGet();
        this.callbackMap.put(Integer.valueOf(iIncrementAndGet), iMqttMessageListener);
        this.callbackTopicMap.put(str, Integer.valueOf(iIncrementAndGet));
        if (num != null) {
            this.subscriptionIdMap.put(num, Integer.valueOf(iIncrementAndGet));
        }
    }

    public void removeMessageListener(String str) {
        Integer num = this.callbackTopicMap.get(str);
        this.callbackMap.remove(num);
        this.callbackTopicMap.remove(str);
        for (Map.Entry<Integer, Integer> entry : this.subscriptionIdMap.entrySet()) {
            if (entry.getValue().equals(num)) {
                this.subscriptionIdMap.remove(entry.getKey());
            }
        }
    }

    public void removeMessageListener(Integer num) {
        Integer num2 = this.subscriptionIdMap.get(num);
        this.subscriptionIdMap.remove(num2);
        this.callbackMap.remove(num2);
        for (Map.Entry<String, Integer> entry : this.callbackTopicMap.entrySet()) {
            if (entry.getValue().equals(num2)) {
                this.callbackTopicMap.remove(entry.getKey());
            }
        }
    }

    public void removeMessageListeners() {
        this.callbackMap.clear();
        this.subscriptionIdMap.clear();
        this.callbackTopicMap.clear();
    }

    protected boolean deliverMessage(String str, int i, MqttMessage mqttMessage) throws Exception {
        boolean z = false;
        if (mqttMessage.getProperties().getSubscriptionIdentifiers().isEmpty()) {
            for (Map.Entry<String, Integer> entry : this.callbackTopicMap.entrySet()) {
                if (MqttTopicValidator.isMatched(entry.getKey(), str)) {
                    mqttMessage.setId(i);
                    this.callbackMap.get(entry.getValue()).messageArrived(str, mqttMessage);
                    z = true;
                }
            }
        } else {
            for (Integer num : mqttMessage.getProperties().getSubscriptionIdentifiers()) {
                if (this.subscriptionIdMap.containsKey(num)) {
                    Integer num2 = this.subscriptionIdMap.get(num);
                    mqttMessage.setId(i);
                    this.callbackMap.get(num2).messageArrived(str, mqttMessage);
                    z = true;
                }
            }
        }
        if (this.mqttCallback == null || z) {
            return z;
        }
        mqttMessage.setId(i);
        try {
            this.mqttCallback.messageArrived(str, mqttMessage);
            return true;
        } catch (Exception e) {
            this.log.fine(CLASS_NAME, "deliverMessage", "725", new Object[]{e});
            return true;
        }
    }

    public boolean doesSubscriptionIdentifierExist(int i) {
        return this.subscriptionIdMap.containsKey(Integer.valueOf(i));
    }

    public boolean isRunning() {
        boolean z;
        synchronized (this.lifecycle) {
            z = (this.current_state == State.RUNNING || this.current_state == State.QUIESCING) && this.target_state == State.RUNNING;
        }
        return z;
    }

    public boolean isQuiescing() {
        boolean z;
        synchronized (this.lifecycle) {
            z = this.current_state == State.QUIESCING;
        }
        return z;
    }
}
