package com.cvte.tv.api;

import a.b.c.a.a;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
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 com.seewo.libmcuservice.LibMcuApplication;
import com.seewo.libmcuservice.aidl.model.McuEnum;
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 int MSG_DISPATCH_NOTIFY = 1;
    private static final String TAG = "MiddleWareApi";
    private Handler mNotifyHandler;
    private HandlerThread mNotifyThread;
    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();

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

        public ApiElement() {
        }
    }

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

        @Override // java.lang.reflect.InvocationHandler
        public Object invoke(Object obj, Method method, Object[] objArr) {
            if (method.getDeclaringClass() == Object.class) {
                return method.invoke(this, objArr);
            }
            if (method.isAnnotationPresent(NotifyAction.class)) {
                ArrayList arrayList = new ArrayList();
                int i2 = 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()[i2];
                            notifyParam.value = objArr[i2];
                            i2++;
                            arrayList.add(notifyParam);
                        }
                    }
                }
                MiddleWareApi.this.invokeNotify(method.getName(), arrayList);
            }
            return method.invoke(((ApiElement) MiddleWareApi.mapApi.get(method.getDeclaringClass())).implObj, objArr);
        }
    }

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

        public NotifyParam() {
        }
    }

    private MiddleWareApi() {
        CONFIG_FILE_PATH = "/etc";
        HashMap map = new HashMap();
        mapApi = map;
        map.clear();
        HandlerThread handlerThread = new HandlerThread("MIDDLEWAREAPI_DISPATCH_NOTIFY");
        this.mNotifyThread = handlerThread;
        handlerThread.start();
        this.mNotifyHandler = new Handler(this.mNotifyThread.getLooper()) { // from class: com.cvte.tv.api.MiddleWareApi.1
            @Override // android.os.Handler
            public void handleMessage(Message message) {
                if (message.what == 1) {
                    String str = (String) message.obj;
                    Bundle data = message.getData();
                    synchronized (MiddleWareApi.listeners) {
                        if (MiddleWareApi.listeners != null && !MiddleWareApi.listeners.isEmpty()) {
                            for (INotifyListener iNotifyListener : MiddleWareApi.listeners) {
                                if (iNotifyListener != null) {
                                    try {
                                        iNotifyListener.onNotify(str, data);
                                    } catch (RemoteException e2) {
                                        MiddleWareApi.this.illegalListeners.add(iNotifyListener);
                                        Log.e(MiddleWareApi.TAG, LibMcuApplication.REMOTE_EXCEPTION, e2);
                                    } catch (Exception e3) {
                                        Log.e(MiddleWareApi.TAG, "Exception", e3);
                                    }
                                }
                            }
                            MiddleWareApi.listeners.removeAll(MiddleWareApi.this.illegalListeners);
                            if (!MiddleWareApi.this.illegalListeners.isEmpty()) {
                                MiddleWareApi.this.illegalListeners.clear();
                            }
                        }
                    }
                }
            }
        };
    }

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

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

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

    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(a.p(str, " (parameter)"), objArr);
    }

    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 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 boolean checkSupportable(Class<?> cls) {
        return mapApi.containsKey(cls);
    }

    public String getCVTEConfigPath() {
        StringBuilder sbC = a.C("TVAPI Get Config Path=");
        sbC.append(CONFIG_FILE_PATH);
        Log.d("Evan", sbC.toString());
        return CONFIG_FILE_PATH;
    }

    public Context getContext() {
        return mContext;
    }

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

    public boolean invokeAllResetMethod(EnumResetLevel enumResetLevel) {
        String str;
        String str2;
        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 str3 : strArrReset) {
                            try {
                                Method declaredMethod = key.getDeclaredMethod(str3, EnumResetLevel.class);
                                if (declaredMethod != null) {
                                    declaredMethod.invoke(entry.getValue().implObj, enumResetLevel);
                                }
                            } catch (IllegalAccessException e2) {
                                e = e2;
                                str = TAG;
                                str2 = "IllegalAccessException";
                                Log.e(str, str2, e);
                            } catch (NoSuchMethodException e3) {
                                e = e3;
                                str = TAG;
                                str2 = "NoSuchMethodException";
                                Log.e(str, str2, e);
                            } catch (InvocationTargetException e4) {
                                e = e4;
                                str = TAG;
                                str2 = "InvocationTargetException";
                                Log.e(str, str2, e);
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

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

    public synchronized void invokeListener(String str, Bundle bundle) {
        Message messageObtainMessage = this.mNotifyHandler.obtainMessage(1, str);
        messageObtainMessage.setData(bundle);
        messageObtainMessage.sendToTarget();
    }

    /* JADX WARN: Multi-variable type inference failed */
    public <T> void registerFunction(Class<T> cls) {
        String str;
        String str2;
        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 e2) {
            e = e2;
            str = TAG;
            str2 = "IllegalAccessException";
            Log.e(str, str2, e);
            timplNewInstance = anonymousClass1;
        } catch (InstantiationException e3) {
            e = e3;
            str = TAG;
            str2 = "InstantiationException";
            Log.e(str, str2, e);
            timplNewInstance = anonymousClass1;
        }
        for (Class<?> cls2 : interfaces) {
            ApiElement apiElement = new ApiElement();
            apiElement.implObj = timplNewInstance;
            apiElement.proxyObj = objNewProxyInstance;
            synchronized (mapApi) {
                mapApi.put(cls2, apiElement);
            }
        }
    }

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

    public void removeNotifyListener(INotifyListener iNotifyListener) {
        List<INotifyListener> list = listeners;
        synchronized (list) {
            try {
                if (iNotifyListener == null) {
                    throw new UnsupportedOperationException("Action or Listener parameter must be not null!");
                }
                Log.d("TifPlayerActivity", "befor removeNotifyListener " + String.valueOf(list.size()));
                list.remove(iNotifyListener);
                Log.d("TifPlayerActivity", "after removeNotifyListener " + String.valueOf(list.size()));
            } catch (Throwable th) {
                throw th;
            }
        }
    }

    public boolean setCVTEConfigPath(String str) {
        CONFIG_FILE_PATH = str;
        StringBuilder sbC = a.C("TVAPI Set Config Path=");
        sbC.append(CONFIG_FILE_PATH);
        Log.d("Evan", sbC.toString());
        return true;
    }
}
