package com.cvte.tv.api;

import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import androidx.constraintlayout.core.motion.utils.TypedValues;
import androidx.core.app.NotificationCompat;
import com.cvte.tv.api.aidl.EnumResetLevel;
import com.cvte.tv.api.aidl.INotifyGlobalKeyListener;
import com.cvte.tv.api.aidl.INotifyListener;
import com.cvte.tv.api.gson.Gson;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/* JADX INFO: loaded from: classes.dex */
public class MiddleWareApi {
    private static String CONFIG_FILE_PATH = null;
    private static final String TAG = "MiddleWareApi";
    private static Gson gson = new Gson();
    private static Map<Class<?>, ApiElement> mapApi = null;
    private static final List<INotifyListener> listeners = new ArrayList();
    private static Context mContext = null;
    private static volatile MiddleWareApi instance = null;
    private List<INotifyListener> illegalListeners = new ArrayList();
    private List<INotifyGlobalKeyListener> globalKeyListeners = new ArrayList();
    Bundle bundle = new Bundle();

    class NotifyParam {
        String name;
        Class<?> type;
        Object value;

        NotifyParam() {
        }
    }

    class ApiElement<TImpl> {
        TImpl implObj = null;
        Object proxyObj = null;

        ApiElement() {
        }
    }

    private MiddleWareApi() {
        CONFIG_FILE_PATH = "/etc";
        HashMap map = new HashMap();
        mapApi = map;
        map.clear();
    }

    public static MiddleWareApi getInstance(Context context) {
        mContext = context;
        Log.i(NotificationCompat.CATEGORY_SERVICE, "Service tv-api-library VerName:1.0.14 VerCode:1490089988");
        return getInstance();
    }

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

    public Context getContext() {
        return mContext;
    }

    public String getCVTEConfigPath() {
        Log.d("Evan", "TVAPI Get Config Path=" + CONFIG_FILE_PATH);
        return CONFIG_FILE_PATH;
    }

    public boolean setCVTEConfigPath(String str) {
        CONFIG_FILE_PATH = str;
        Log.d("Evan", "TVAPI Set Config Path=" + CONFIG_FILE_PATH);
        return true;
    }

    public boolean invokeAllResetMethod(EnumResetLevel enumResetLevel) {
        synchronized (mapApi) {
            for (Map.Entry<Class<?>, ApiElement> entry : mapApi.entrySet()) {
                Class<?> key = entry.getKey();
                for (Annotation annotation : key.getDeclaredAnnotations()) {
                    if (ResetAction.class == annotation.annotationType()) {
                        String[] strArrReset = ((ResetAction) annotation).reset();
                        if (strArrReset == null || strArrReset.length < 1) {
                            throw new IllegalAccessError("Must add one or more reset action method at interface:#<" + key.getName() + ">");
                        }
                        for (String str : strArrReset) {
                            try {
                                try {
                                    Method declaredMethod = key.getDeclaredMethod(str, EnumResetLevel.class);
                                    if (declaredMethod != null) {
                                        declaredMethod.invoke(entry.getValue().implObj, enumResetLevel);
                                    }
                                } catch (InvocationTargetException e) {
                                    Log.e(TAG, "InvocationTargetException", e);
                                }
                            } catch (IllegalAccessException e2) {
                                Log.e(TAG, "IllegalAccessException", e2);
                            } catch (NoSuchMethodException e3) {
                                Log.e(TAG, "NoSuchMethodException", e3);
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    public synchronized boolean invokeGlobalKeyListener(KeyEvent keyEvent) {
        boolean z;
        List<INotifyGlobalKeyListener> list = this.globalKeyListeners;
        z = false;
        if (list != null && !list.isEmpty()) {
            Iterator<INotifyGlobalKeyListener> it = this.globalKeyListeners.iterator();
            while (it.hasNext()) {
                try {
                    if (it.next().handleKeyEvent(keyEvent)) {
                        z = true;
                    }
                } catch (RemoteException e) {
                    Log.e(TAG, "RemoteException", e);
                    it.remove();
                }
            }
        }
        return z;
    }

    public synchronized void addNotifyGlobalKeyListener(INotifyGlobalKeyListener iNotifyGlobalKeyListener) {
        if (iNotifyGlobalKeyListener == null) {
            throw new UnsupportedOperationException("global Key Listener parameter must be not null!");
        }
        this.globalKeyListeners.add(iNotifyGlobalKeyListener);
    }

    public synchronized void removeNotifyGlobalKeyListener(INotifyGlobalKeyListener iNotifyGlobalKeyListener) {
        if (iNotifyGlobalKeyListener == null) {
            throw new UnsupportedOperationException("global Key Listener parameter must be not null!");
        }
        this.globalKeyListeners.remove(iNotifyGlobalKeyListener);
    }

    /* JADX WARN: Multi-variable type inference failed */
    public <T> void registerFunction(Class<T> cls) {
        TImpl timplNewInstance;
        if (cls == null) {
            throw new IllegalAccessError("implClz must not null!");
        }
        Class<?>[] interfaces = cls.getInterfaces();
        if (interfaces == null || interfaces.length < 1) {
            throw new IllegalAccessError("must implement one or more function api!");
        }
        AnonymousClass1 anonymousClass1 = (T) null;
        Object objNewProxyInstance = Proxy.newProxyInstance(cls.getClassLoader(), interfaces, new FunctionHandler());
        try {
            timplNewInstance = cls.newInstance();
        } catch (IllegalAccessException e) {
            Log.e(TAG, "IllegalAccessException", e);
            timplNewInstance = anonymousClass1;
        } catch (InstantiationException e2) {
            Log.e(TAG, "InstantiationException", e2);
            timplNewInstance = anonymousClass1;
        }
        for (Class<?> cls2 : interfaces) {
            ApiElement apiElement = new ApiElement();
            apiElement.implObj = timplNewInstance;
            apiElement.proxyObj = objNewProxyInstance;
            synchronized (mapApi) {
                mapApi.put(cls2, apiElement);
            }
        }
    }

    /* JADX WARN: Removed duplicated region for block: B:22:0x004d A[Catch: all -> 0x0052, DONT_GENERATE, TRY_LEAVE, TryCatch #0 {all -> 0x0052, RemoteException -> 0x002b, Exception -> 0x0022, blocks: (B:6:0x0006, B:8:0x000c, B:9:0x0010, B:11:0x0016, B:13:0x001e, B:16:0x0023, B:18:0x002c, B:19:0x0039, B:21:0x0048, B:22:0x004d), top: B:32:0x0006, outer: #1 }] */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public synchronized void invokeListener(java.lang.String r6, android.os.Bundle r7) {
        /*
            r5 = this;
            monitor-enter(r5)
            java.util.List<com.cvte.tv.api.aidl.INotifyListener> r0 = com.cvte.tv.api.MiddleWareApi.listeners     // Catch: java.lang.Throwable -> L54
            monitor-enter(r0)     // Catch: java.lang.Throwable -> L54
            if (r0 == 0) goto L4d
            boolean r1 = r0.isEmpty()     // Catch: java.lang.Throwable -> L52
            if (r1 != 0) goto L4d
            java.util.Iterator r1 = r0.iterator()     // Catch: java.lang.Throwable -> L52
        L10:
            boolean r2 = r1.hasNext()     // Catch: java.lang.Throwable -> L52
            if (r2 == 0) goto L39
            java.lang.Object r2 = r1.next()     // Catch: java.lang.Throwable -> L52
            com.cvte.tv.api.aidl.INotifyListener r2 = (com.cvte.tv.api.aidl.INotifyListener) r2     // Catch: java.lang.Throwable -> L52
            if (r2 == 0) goto L10
            r2.onNotify(r6, r7)     // Catch: java.lang.Exception -> L22 android.os.RemoteException -> L2b java.lang.Throwable -> L52
            goto L10
        L22:
            r2 = move-exception
            java.lang.String r3 = "MiddleWareApi"
            java.lang.String r4 = "Exception"
            android.util.Log.e(r3, r4, r2)     // Catch: java.lang.Throwable -> L52
            goto L10
        L2b:
            r3 = move-exception
            java.util.List<com.cvte.tv.api.aidl.INotifyListener> r4 = r5.illegalListeners     // Catch: java.lang.Throwable -> L52
            r4.add(r2)     // Catch: java.lang.Throwable -> L52
            java.lang.String r2 = "MiddleWareApi"
            java.lang.String r4 = "RemoteException"
            android.util.Log.e(r2, r4, r3)     // Catch: java.lang.Throwable -> L52
            goto L10
        L39:
            java.util.List<com.cvte.tv.api.aidl.INotifyListener> r6 = com.cvte.tv.api.MiddleWareApi.listeners     // Catch: java.lang.Throwable -> L52
            java.util.List<com.cvte.tv.api.aidl.INotifyListener> r7 = r5.illegalListeners     // Catch: java.lang.Throwable -> L52
            r6.removeAll(r7)     // Catch: java.lang.Throwable -> L52
            java.util.List<com.cvte.tv.api.aidl.INotifyListener> r6 = r5.illegalListeners     // Catch: java.lang.Throwable -> L52
            boolean r6 = r6.isEmpty()     // Catch: java.lang.Throwable -> L52
            if (r6 != 0) goto L4d
            java.util.List<com.cvte.tv.api.aidl.INotifyListener> r6 = r5.illegalListeners     // Catch: java.lang.Throwable -> L52
            r6.clear()     // Catch: java.lang.Throwable -> L52
        L4d:
            monitor-exit(r0)     // Catch: java.lang.Throwable -> L52
            monitor-exit(r5)
            return
        L50:
            monitor-exit(r0)     // Catch: java.lang.Throwable -> L52
            throw r6     // Catch: java.lang.Throwable -> L54
        L52:
            r6 = move-exception
            goto L50
        L54:
            r6 = move-exception
            monitor-exit(r5)     // Catch: java.lang.Throwable -> L54
            throw r6
        */
        throw new UnsupportedOperationException("Method not decompiled: com.cvte.tv.api.MiddleWareApi.invokeListener(java.lang.String, android.os.Bundle):void");
    }

    public void addNotifyListener(INotifyListener iNotifyListener) {
        List<INotifyListener> list = listeners;
        synchronized (list) {
            if (iNotifyListener == null) {
                throw new UnsupportedOperationException("Action or Listener parameter must be not null!");
            }
            list.add(iNotifyListener);
        }
    }

    public void removeNotifyListener(INotifyListener iNotifyListener) {
        List<INotifyListener> list = listeners;
        synchronized (list) {
            if (iNotifyListener == null) {
                throw new UnsupportedOperationException("Action or Listener parameter must be not null!");
            }
            list.remove(iNotifyListener);
        }
    }

    public boolean checkSupportable(Class<?> cls) {
        return mapApi.containsKey(cls);
    }

    public <T> T getTvApi(Class<T> cls) {
        ApiElement apiElement = mapApi.get(cls);
        if (apiElement == null) {
            return null;
        }
        return (T) apiElement.proxyObj;
    }

    private class FunctionHandler implements InvocationHandler {
        private FunctionHandler() {
        }

        @Override // java.lang.reflect.InvocationHandler
        public Object invoke(Object obj, Method method, Object[] objArr) throws Throwable {
            if (method.getDeclaringClass() == Object.class) {
                return method.invoke(this, objArr);
            }
            if (method.isAnnotationPresent(NotifyAction.class)) {
                ArrayList arrayList = new ArrayList();
                int i = 0;
                for (Annotation[] annotationArr : method.getParameterAnnotations()) {
                    for (Annotation annotation : annotationArr) {
                        if (annotation.annotationType() == NotifyParams.class) {
                            NotifyParam notifyParam = MiddleWareApi.this.new NotifyParam();
                            notifyParam.name = ((NotifyParams) annotation).value();
                            notifyParam.type = method.getParameterTypes()[i];
                            notifyParam.value = objArr[i];
                            i++;
                            arrayList.add(notifyParam);
                        }
                    }
                }
                MiddleWareApi.this.invokeNotify(method.getName(), arrayList);
            }
            return method.invoke(((ApiElement) MiddleWareApi.mapApi.get(method.getDeclaringClass())).implObj, objArr);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public synchronized void invokeNotify(String str, List<NotifyParam> list) {
        if (list.isEmpty()) {
            invokeListener(str, null);
        } else {
            this.bundle.clear();
            for (NotifyParam notifyParam : list) {
                if (notifyParam.value == null) {
                    this.bundle.putString(notifyParam.name, null);
                } else {
                    String simpleName = notifyParam.type.getSimpleName();
                    if (notifyParam.type.isPrimitive()) {
                        String string = notifyParam.value.toString();
                        if (TypedValues.Custom.S_BOOLEAN.equals(simpleName)) {
                            this.bundle.putBoolean(notifyParam.name, Boolean.parseBoolean(string));
                        } else if ("char".equals(simpleName)) {
                            this.bundle.putChar(notifyParam.name, string.charAt(0));
                        } else if ("byte".equals(simpleName)) {
                            this.bundle.putByte(notifyParam.name, Byte.parseByte(string));
                        } else if ("short".equals(simpleName)) {
                            this.bundle.putShort(notifyParam.name, Short.parseShort(string));
                        } else if ("int".equals(simpleName)) {
                            this.bundle.putInt(notifyParam.name, Integer.parseInt(string));
                        } else if ("long".equals(simpleName)) {
                            this.bundle.putLong(notifyParam.name, Long.parseLong(string));
                        } else if (TypedValues.Custom.S_FLOAT.equals(simpleName)) {
                            this.bundle.putFloat(notifyParam.name, Float.parseFloat(string));
                        } else if ("double".equals(simpleName)) {
                            this.bundle.putDouble(notifyParam.name, Double.parseDouble(string));
                        }
                    }
                    if ("String".equals(simpleName) || (notifyParam.value instanceof Enum)) {
                        this.bundle.putString(notifyParam.name, notifyParam.value.toString());
                    } else if ("int[]".equals(simpleName)) {
                        this.bundle.putIntArray(notifyParam.name, (int[]) notifyParam.value);
                    } else {
                        try {
                            this.bundle.putString(notifyParam.name, gson.toJson(notifyParam.value));
                        } catch (Exception e) {
                            Log.e(TAG, "Exception", e);
                            throw parameterError("No support %s type parameter:<%s>", simpleName, notifyParam.name);
                        }
                    }
                }
            }
            invokeListener(str, this.bundle);
            this.bundle.clear();
        }
    }

    private RuntimeException methodError(String str, Object... objArr) {
        if (objArr.length > 0) {
            str = String.format(str, objArr);
        }
        return new IllegalArgumentException(str);
    }

    private RuntimeException parameterError(String str, Object... objArr) {
        return methodError(str + " (parameter)", objArr);
    }
}
