package com.seewo.sdk;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import com.seewo.sdk.eventbus.EventBusRuntimeException;
import com.seewo.sdk.eventbus.OnEventOfOS;
import com.seewo.sdk.eventbus.ThreadMode;
import com.seewo.sdk.interfaces.IEventBus;
import com.seewo.sdk.internal.command.common.CmdPostEvent;
import com.seewo.sdk.internal.model.LibMcuCallback;
import com.seewo.sdk.internal.model.SDKResponse;
import com.seewo.sdk.util.ParseUtil;
import com.seewo.sdk.util.RLog;
import d.b.a.a.a;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;

/* JADX INFO: loaded from: classes.dex */
public class OsEventBus implements IEventBus {
    private static final String TAG = "OsEventBus";
    private static OsEventBus sInstance;
    private final Map<Class, CopyOnWriteArrayList<Subscription>> mSubscriptionsByEventType = new HashMap();
    private Map<Class, LibMcuCallback.Stub> mLibMcuCallbackMap = new HashMap();
    private final Map<Object, List<Class<?>>> mTypesBySubscriber = new HashMap();
    private HandlerPoster mMainThreadPoster = new HandlerPoster(Looper.getMainLooper(), 10);
    private HandlerPoster mBackgroundThreadPoster = new HandlerPoster(BackgroundThread.get().getLooper(), 10);

    /* JADX INFO: renamed from: com.seewo.sdk.OsEventBus$3, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass3 {
        public static final /* synthetic */ int[] $SwitchMap$com$seewo$sdk$eventbus$ThreadMode;

        static {
            ThreadMode.values();
            int[] iArr = new int[2];
            $SwitchMap$com$seewo$sdk$eventbus$ThreadMode = iArr;
            try {
                iArr[ThreadMode.MAIN.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$seewo$sdk$eventbus$ThreadMode[ThreadMode.BACKGROUND.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
        }
    }

    public static final class HandlerPoster extends Handler {
        private boolean handlerActive;
        private final int maxMillisInsideHandleMessage;
        private final ConcurrentLinkedQueue<PendingPost> queue;

        public HandlerPoster(Looper looper, int i2) {
            super(looper);
            this.queue = new ConcurrentLinkedQueue<>();
            this.maxMillisInsideHandleMessage = i2;
        }

        private PendingPost getPendingPost() {
            PendingPost pendingPostPoll = this.queue.poll();
            if (pendingPostPoll == null) {
                synchronized (this) {
                    pendingPostPoll = this.queue.poll();
                    if (pendingPostPoll == null) {
                        this.handlerActive = false;
                        return null;
                    }
                }
            }
            return pendingPostPoll;
        }

        public void enqueue(Subscription subscription, Object obj) {
            PendingPost pendingPostObtainPendingPost = PendingPost.obtainPendingPost(subscription, obj);
            synchronized (this) {
                this.queue.add(pendingPostObtainPendingPost);
                if (!this.handlerActive) {
                    this.handlerActive = true;
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusRuntimeException("Could not send handler message");
                    }
                }
            }
        }

        @Override // android.os.Handler
        public void handleMessage(Message message) {
            try {
                long jUptimeMillis = SystemClock.uptimeMillis();
                do {
                    PendingPost pendingPost = getPendingPost();
                    if (pendingPost == null) {
                        return;
                    }
                    Object obj = pendingPost.event;
                    Subscription subscription = pendingPost.subscription;
                    PendingPost.releasePendingPost(pendingPost);
                    if (subscription != null && subscription.active) {
                        OsEventBus.getInstance().invokeSubscriber(subscription, obj);
                    }
                } while (SystemClock.uptimeMillis() - jUptimeMillis < this.maxMillisInsideHandleMessage);
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusRuntimeException("Could not send handler message");
                }
                this.handlerActive = true;
            } finally {
                this.handlerActive = false;
            }
        }
    }

    public interface OSEventCallback<T> {
        void onEvent(T t);
    }

    public static class PendingPost {
        private static final List<PendingPost> pendingPostPool = new ArrayList();
        public Object event;
        public PendingPost next;
        public Subscription subscription;

        private PendingPost(Object obj, Subscription subscription) {
            this.event = obj;
            this.subscription = subscription;
        }

        public static PendingPost obtainPendingPost(Subscription subscription, Object obj) {
            List<PendingPost> list = pendingPostPool;
            synchronized (list) {
                int size = list.size();
                if (size <= 0) {
                    return new PendingPost(obj, subscription);
                }
                PendingPost pendingPostRemove = list.remove(size - 1);
                pendingPostRemove.event = obj;
                pendingPostRemove.subscription = subscription;
                pendingPostRemove.next = null;
                return pendingPostRemove;
            }
        }

        public static void releasePendingPost(PendingPost pendingPost) {
            pendingPost.event = null;
            pendingPost.subscription = null;
            pendingPost.next = null;
            List<PendingPost> list = pendingPostPool;
            synchronized (list) {
                if (list.size() < 10000) {
                    list.add(pendingPost);
                }
            }
        }
    }

    public final class Subscription {
        public volatile boolean active = true;
        public final Object subscriber;
        public final SubscriberMethod subscriberMethod;

        public Subscription(Object obj, SubscriberMethod subscriberMethod) {
            this.subscriber = obj;
            this.subscriberMethod = subscriberMethod;
        }

        public boolean equals(Object obj) {
            if (!(obj instanceof Subscription)) {
                return false;
            }
            Subscription subscription = (Subscription) obj;
            return this.subscriber == subscription.subscriber && this.subscriberMethod.equals(subscription.subscriberMethod);
        }

        public int hashCode() {
            return this.subscriberMethod.hashCode() + this.subscriber.hashCode();
        }
    }

    private OsEventBus() {
    }

    private void checkMethod(Method method) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length != 1) {
            StringBuilder sbB = a.B("@Subscribe method ");
            sbB.append(method.getName());
            sbB.append("must have exactly 1 parameter but has ");
            sbB.append(parameterTypes.length);
            throw new EventBusRuntimeException(sbB.toString());
        }
        int modifiers = method.getModifiers();
        if ((modifiers & 1) == 0 || (modifiers & 1096) > 0) {
            throw new EventBusRuntimeException(method.getName() + " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }

    private void dispose(Object obj, List<Class<?>> list) {
        for (Class<?> cls : list) {
            LibMcuCallback.Stub stubRemove = this.mLibMcuCallbackMap.remove(cls);
            if (stubRemove != null) {
                OpenSDK.getInstance().unregisterCallback(cls, stubRemove);
            }
            unsubscribeByEventType(obj, cls);
        }
        this.mTypesBySubscriber.remove(obj);
    }

    public static OsEventBus getInstance() {
        if (sInstance == null) {
            synchronized (OsEventBus.class) {
                if (sInstance == null) {
                    sInstance = new OsEventBus();
                }
            }
        }
        return sInstance;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public synchronized void post(Object obj) {
        if (!postSingleEventForEventType(obj)) {
            Log.e(TAG, "No subscribers registered for event " + obj.getClass());
        }
    }

    private boolean postSingleEventForEventType(Object obj) {
        CopyOnWriteArrayList<Subscription> copyOnWriteArrayList;
        Class<?> cls = obj.getClass();
        synchronized (this) {
            copyOnWriteArrayList = this.mSubscriptionsByEventType.get(cls);
        }
        if (copyOnWriteArrayList == null || copyOnWriteArrayList.isEmpty()) {
            return false;
        }
        Iterator<Subscription> it = copyOnWriteArrayList.iterator();
        while (it.hasNext()) {
            postToSubscription(it.next(), obj);
        }
        return true;
    }

    private void postToSubscription(Subscription subscription, Object obj) {
        ThreadMode threadMode = subscription.subscriberMethod.threadMode;
        int iOrdinal = threadMode.ordinal();
        if (iOrdinal == 0) {
            this.mMainThreadPoster.enqueue(subscription, obj);
        } else {
            if (iOrdinal == 1) {
                this.mBackgroundThreadPoster.enqueue(subscription, obj);
                return;
            }
            throw new IllegalStateException("Unknown thread mode: " + threadMode);
        }
    }

    private void subscribe(Object obj, SubscriberMethod subscriberMethod) {
        Class<?> cls = subscriberMethod.eventType;
        Subscription subscription = new Subscription(obj, subscriberMethod);
        CopyOnWriteArrayList<Subscription> copyOnWriteArrayList = this.mSubscriptionsByEventType.get(cls);
        if (copyOnWriteArrayList == null) {
            copyOnWriteArrayList = new CopyOnWriteArrayList<>();
            this.mSubscriptionsByEventType.put(cls, copyOnWriteArrayList);
        } else if (copyOnWriteArrayList.contains(subscription)) {
            StringBuilder sbB = a.B("Subscriber ");
            sbB.append(obj.getClass());
            sbB.append(" already registered to event ");
            sbB.append(cls);
            throw new EventBusRuntimeException(sbB.toString());
        }
        List<Class<?>> arrayList = this.mTypesBySubscriber.get(obj);
        if (arrayList == null) {
            arrayList = new ArrayList<>();
            this.mTypesBySubscriber.put(obj, arrayList);
        }
        arrayList.add(cls);
        copyOnWriteArrayList.add(subscription);
    }

    private void unsubscribeByEventType(Object obj, Class<?> cls) {
        CopyOnWriteArrayList<Subscription> copyOnWriteArrayList = this.mSubscriptionsByEventType.get(cls);
        if (copyOnWriteArrayList != null) {
            for (Subscription subscription : copyOnWriteArrayList) {
                if (subscription.subscriber == obj) {
                    subscription.active = false;
                    copyOnWriteArrayList.remove(subscription);
                }
            }
        }
    }

    @Override // com.seewo.sdk.interfaces.IEventBus
    public void broadcast(Object obj) {
        OpenSDK.getInstance().postCommand(new CmdPostEvent(obj), null);
    }

    public void invokeSubscriber(Subscription subscription, Object obj) {
        try {
            subscription.subscriberMethod.invoke(subscription.subscriber, obj);
        } catch (IllegalAccessException e2) {
            throw new IllegalStateException("Unexpected exception", e2);
        } catch (InvocationTargetException e3) {
            throw new EventBusRuntimeException(e3);
        }
    }

    @Override // com.seewo.sdk.interfaces.IEventBus
    public synchronized boolean isRegistered(Object obj) {
        return this.mTypesBySubscriber.containsKey(obj);
    }

    @Override // com.seewo.sdk.interfaces.IEventBus
    public synchronized void register(Object obj) {
        if (isRegistered(obj)) {
            RLog.e(TAG, obj.getClass().getSimpleName() + " has been registered. It can not be registered again");
            return;
        }
        for (Method method : obj.getClass().getDeclaredMethods()) {
            OnEventOfOS onEventOfOS = (OnEventOfOS) method.getAnnotation(OnEventOfOS.class);
            if (onEventOfOS != null) {
                checkMethod(method);
                Class<?> cls = method.getParameterTypes()[0];
                subscribe(obj, new SubscriberMethod(cls, method, onEventOfOS.threadMode()));
                LibMcuCallback.Stub stub = new LibMcuCallback.Stub() { // from class: com.seewo.sdk.OsEventBus.1
                    @Override // com.seewo.sdk.internal.model.LibMcuCallback
                    public void onCall(String str) throws RemoteException {
                        SDKResponse sDKResponse = (SDKResponse) ParseUtil.decodeJSON(str, SDKResponse.class);
                        try {
                            OsEventBus.this.post(d.a.a.a.g(sDKResponse.getParamsJson(), Class.forName(sDKResponse.getResponseName())));
                        } catch (ClassNotFoundException e2) {
                            Log.e(OsEventBus.TAG, "Error: ", e2);
                        }
                    }
                };
                this.mLibMcuCallbackMap.put(cls, stub);
                OpenSDK.getInstance().registerCallback(cls, stub);
            }
        }
        if (!isRegistered(obj)) {
            RLog.e(TAG, obj.getClass().getSimpleName() + " has no OnEventOfOS method(s) to been registered! Register failed!");
        }
    }

    public synchronized <T> void registerCallback(Class<T> cls, OSEventCallback<T> oSEventCallback) {
        registerCallback(cls, ThreadMode.BACKGROUND, oSEventCallback);
    }

    public synchronized void unRegisterCallback(OSEventCallback<?> oSEventCallback) {
        List<Class<?>> list = this.mTypesBySubscriber.get(oSEventCallback);
        if (list != null) {
            dispose(oSEventCallback, list);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + oSEventCallback.getClass());
        }
    }

    @Override // com.seewo.sdk.interfaces.IEventBus
    public synchronized void unregister(Object obj) {
        if (!isRegistered(obj)) {
            RLog.e(TAG, obj.getClass().getSimpleName() + " has not been registered. It can not be unregistered");
            return;
        }
        List<Class<?>> list = this.mTypesBySubscriber.get(obj);
        if (list != null) {
            dispose(obj, list);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + obj.getClass());
        }
    }

    public synchronized <T> void registerCallback(Class<T> cls, ThreadMode threadMode, OSEventCallback<T> oSEventCallback) {
        subscribe(oSEventCallback, new SubscriberMethod((Class<?>) cls, (OSEventCallback) oSEventCallback, threadMode));
        LibMcuCallback.Stub stub = new LibMcuCallback.Stub() { // from class: com.seewo.sdk.OsEventBus.2
            @Override // com.seewo.sdk.internal.model.LibMcuCallback
            public void onCall(String str) throws RemoteException {
                SDKResponse sDKResponse = (SDKResponse) ParseUtil.decodeJSON(str, SDKResponse.class);
                try {
                    OsEventBus.this.post(d.a.a.a.g(sDKResponse.getParamsJson(), Class.forName(sDKResponse.getResponseName())));
                } catch (ClassNotFoundException e2) {
                    Log.e(OsEventBus.TAG, "Error: ", e2);
                }
            }
        };
        this.mLibMcuCallbackMap.put(cls, stub);
        OpenSDK.getInstance().registerCallback(cls, stub);
    }

    public class SubscriberMethod {
        public OSEventCallback eventCallback;
        public Class<?> eventType;
        public Method method;
        public ThreadMode threadMode;

        public SubscriberMethod(Class<?> cls, Method method, ThreadMode threadMode) {
            this.eventType = cls;
            this.method = method;
            this.threadMode = threadMode;
        }

        public boolean equals(Object obj) {
            return obj == this || ((obj instanceof SubscriberMethod) && toString().equals(obj.toString()));
        }

        public int hashCode() {
            Method method = this.method;
            return method != null ? method.hashCode() : this.eventCallback.hashCode();
        }

        public void invoke(Object obj, Object obj2) throws IllegalAccessException, InvocationTargetException {
            Method method = this.method;
            if (method != null) {
                method.invoke(obj, obj2);
            } else {
                this.eventCallback.onEvent(obj2);
            }
        }

        public String toString() {
            if (this.method == null) {
                StringBuilder sbB = a.B("SubscriberMethod{eventType=");
                sbB.append(this.eventType.getName());
                sbB.append(", threadMode=");
                sbB.append(this.threadMode.name());
                sbB.append(", eventCallback=");
                sbB.append(this.eventCallback);
                sbB.append('}');
                return sbB.toString();
            }
            return this.method.getDeclaringClass().getName() + '.' + this.method.getName() + '(' + this.eventType.getName() + ") in " + this.threadMode.name();
        }

        public SubscriberMethod(Class<?> cls, OSEventCallback oSEventCallback, ThreadMode threadMode) {
            this.eventType = cls;
            this.threadMode = threadMode;
            this.eventCallback = oSEventCallback;
        }
    }
}
