// Created by Jakub Domaszewicz
package com.aidlab.unity;

import android.os.Handler;
import android.os.HandlerThread;

import com.aidlab.sdk.DeviceDelegate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Calls a device delegate on a thread of its own instead of the main thread the Aidlab SDK calls it on. A call of a
 * Unity AndroidJavaProxy takes about 9 ms on Android's main thread and 0.1 ms on another (Galaxy A14), so one call per
 * sample on the main thread falls ever further behind a strap. One thread serves every device, so the callbacks keep
 * the order the SDK made them in.
 */
public final class BackgroundDelegate {
    private static final Handler handler;

    static {
        HandlerThread thread = new HandlerThread("AidlabUnityCallbacks");
        thread.start();
        handler = new Handler(thread.getLooper());
    }

    private BackgroundDelegate() {
    }

    public static DeviceDelegate wrap(final DeviceDelegate target) {
        return (DeviceDelegate) Proxy.newProxyInstance(
                DeviceDelegate.class.getClassLoader(),
                new Class<?>[]{DeviceDelegate.class},
                (proxy, method, args) -> {
                    if (method.getDeclaringClass() == Object.class) {
                        return method.invoke(target, args);
                    }
                    handler.post(() -> call(target, method, args));
                    return null;
                });
    }

    private static void call(DeviceDelegate target, Method method, Object[] args) {
        try {
            method.invoke(target, args);
        } catch (InvocationTargetException exception) {
            throw new RuntimeException(exception.getCause());
        } catch (IllegalAccessException exception) {
            throw new RuntimeException(exception);
        }
    }
}
