#if UNITY_ANDROID && !UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Android;

namespace Aidlab
{
    internal sealed class AndroidAidlabBackend
    {
        private const string BluetoothScanPermission = "android.permission.BLUETOOTH_SCAN";
        private const string BluetoothConnectPermission = "android.permission.BLUETOOTH_CONNECT";

        private readonly AidlabSDK owner;
        private readonly object commandCallbacksLock = new object();
        private readonly HashSet<CommandCallbackProxy> commandCallbacks = new HashSet<CommandCallbackProxy>();

        // The connection to the device the scan handed over, from connect until it ends or this backend abandons it;
        // null while the backend waits for a device. State changes run on the Unity main thread.
        private Session session;
        private string targetDeviceName;
        private readonly string targetDeviceAddress;
        private string status = "WaitingForPermissions";
        private string lastError = "";
        private bool disposed;

        internal AndroidAidlabBackend(AidlabSDK owner, string targetDeviceName, string targetDeviceAddress)
        {
            this.owner = owner ?? throw new ArgumentNullException(nameof(owner));
            this.targetDeviceName = targetDeviceName ?? "";
            this.targetDeviceAddress = targetDeviceAddress ?? "";
        }

        internal bool IsConnected => session != null;
        internal string Status => status;
        internal string LastError => lastError;

        internal void Update()
        {
            if (disposed || session != null)
                return;

            SharedScan.Wait(this);
        }

        internal void SetTargetDeviceName(string value)
        {
            targetDeviceName = value ?? "";
            ResetConnection();
        }

        internal Task<int?> Collect(Signal[] liveSignals, Signal[] syncSignals, DeviceEventType[] events)
        {
            if (session == null)
                return NotConnectedTask();

            AndroidJavaObject live = BuildEnumSet("com.aidlab.sdk.DataType", liveSignals, AndroidDataTypeName);
            AndroidJavaObject sync = BuildEnumSet("com.aidlab.sdk.DataType", syncSignals, AndroidDataTypeName);
            AndroidJavaObject javaEvents = BuildEnumSet("com.aidlab.sdk.DeviceEventType", events, AndroidEventTypeName);
            try
            {
                return CallCommand("collect", live, sync, javaEvents);
            }
            finally
            {
                live.Dispose();
                sync.Dispose();
                javaEvents.Dispose();
            }
        }

        internal Task<int?> StartSynchronization()
        {
            return CallCommand("startSynchronization");
        }

        internal Task<int?> StopSynchronization()
        {
            return CallCommand("stopSynchronization");
        }

        internal Task<int?> ClearSynchronization()
        {
            return CallCommand("clearSynchronization");
        }

        internal Task<int?> StopCollect()
        {
            return CallCommand("stopCollect");
        }

        internal Task Send(byte[] payload, int processId)
        {
            return CallCommand("send", payload, processId);
        }

        internal void Shutdown()
        {
            disposed = true;
            SharedScan.Leave(this);
            ResetConnection();

            lock (commandCallbacksLock)
            {
                var pending = new List<CommandCallbackProxy>(commandCallbacks);
                commandCallbacks.Clear();
                foreach (CommandCallbackProxy callback in pending)
                    callback.Fail(new InvalidOperationException("Android backend was shut down"));
            }
        }

        // The device with the target address, or without an address one with the target name. The Android scan finds
        // only Aidlab devices, so an empty target name accepts any of them.
        private bool Accepts(string deviceName, string deviceAddress)
        {
            if (targetDeviceAddress.Length > 0)
                return string.Equals(deviceAddress, targetDeviceAddress, StringComparison.OrdinalIgnoreCase);
            return string.IsNullOrEmpty(targetDeviceName) ||
                   string.Equals(deviceName, targetDeviceName, StringComparison.OrdinalIgnoreCase);
        }

        private void OnScanning()
        {
            lastError = "";
            status = "Scanning";
        }

        // The scan held the device for this backend.
        private void Connect(AndroidJavaObject device, string address)
        {
            var connecting = new Session(device, address);
            session = connecting;
            status = "Connecting";
            // On a thread of its own: on the main thread a proxy call is too slow for one call per sample.
            using (var callbacks = new AndroidJavaClass("com.aidlab.unity.BackgroundDelegate"))
            using (AndroidJavaObject deviceDelegate =
                   callbacks.CallStatic<AndroidJavaObject>("wrap", new DeviceDelegateProxy(this, connecting)))
                device.Call("connect", deviceDelegate, new ConnectCallbackProxy(this, connecting));
        }

        private void OnConnected(Session connected)
        {
            // An abandoned session disconnects on its own; its didDisconnect releases the device.
            if (connected != session)
                return;

            status = "Connected";
            lastError = "";
            owner.DeviceAddress = connected.Address;
            owner.AndroidDidConnect(
                ReadStringProperty(connected.Device, "firmwareRevision"),
                ReadStringProperty(connected.Device, "hardwareRevision")
            );
        }

        // A failed connection never reached didConnect, so it reports an error instead of a disconnect.
        private void OnConnectFailed(Session failed, string message)
        {
            failed.End();
            if (failed != session)
                return;

            session = null;
            ReportError(AidlabAPI.AidlabErrorCode.Transport, message ?? "Connection failed");
        }

        private void OnDisconnected(Session ended)
        {
            ended.End();
            if (ended != session)
                return;

            session = null;
            status = "Disconnected";
            owner.AndroidDidDisconnect();
        }

        private void ResetConnection()
        {
            SharedScan.AllowPermissionRequest();
            if (session != null)
            {
                session.Device.Call("disconnect");
                session = null;
            }

            status = disposed ? "Stopped" : "Disconnected";
        }

        private Task<int?> CallCommand(string methodName, params object[] args)
        {
            if (session == null)
                return NotConnectedTask();

            var callback = new CommandCallbackProxy(RemoveCommandCallback);
            lock (commandCallbacksLock)
                commandCallbacks.Add(callback);

            var callArgs = new object[args.Length + 1];
            Array.Copy(args, callArgs, args.Length);
            callArgs[args.Length] = callback;

            try
            {
                session.Device.Call(methodName, callArgs);
            }
            catch (Exception exception)
            {
                RemoveCommandCallback(callback);
                callback.Fail(exception);
            }

            return callback.Task;
        }

        private void RemoveCommandCallback(CommandCallbackProxy callback)
        {
            lock (commandCallbacksLock)
                commandCallbacks.Remove(callback);
        }

        private static Task<int?> NotConnectedTask()
        {
            return Task.FromException<int?>(new InvalidOperationException("SDK is not initialized"));
        }

        private static AndroidJavaObject BuildEnumSet<T>(string className, T[] values, Func<T, string> constantName)
        {
            using (var classClass = new AndroidJavaClass("java.lang.Class"))
            using (var enumSetClass = new AndroidJavaClass("java.util.EnumSet"))
            using (var enumClass = new AndroidJavaClass(className))
            using (AndroidJavaObject javaEnumClass = classClass.CallStatic<AndroidJavaObject>("forName", className))
            {
                AndroidJavaObject result =
                    enumSetClass.CallStatic<AndroidJavaObject>("noneOf", javaEnumClass);

                if (values == null)
                    return result;

                foreach (T value in values)
                {
                    string name = constantName(value);
                    if (name == null)
                        continue;

                    using (AndroidJavaObject constant = enumClass.GetStatic<AndroidJavaObject>(name))
                    {
                        result.Call<bool>("add", constant);
                    }
                }

                return result;
            }
        }

        private static string AndroidDataTypeName(Signal signal)
        {
            switch (signal)
            {
                case Signal.Ecg: return "ECG";
                case Signal.Respiration: return "RESPIRATION";
                case Signal.Temperature: return "SKIN_TEMPERATURE";
                case Signal.Motion: return "MOTION";
                case Signal.Orientation: return "ORIENTATION";
                case Signal.Steps: return "STEPS";
                case Signal.HeartRate: return "HEART_RATE";
                case Signal.SoundVolume: return "SOUND_VOLUME";
                case Signal.Rr: return "RR";
                case Signal.Pressure: return "PRESSURE";
                case Signal.RespirationRate: return "RESPIRATION_RATE";
                case Signal.BodyPosition: return "BODY_POSITION";
                case Signal.Eda: return "EDA";
                case Signal.Gps: return "GPS";
                default: return null;
            }
        }

        private static string AndroidEventTypeName(DeviceEventType eventType)
        {
            switch (eventType)
            {
                case DeviceEventType.WearState: return "WEAR_STATE";
                case DeviceEventType.PressureWearState: return "PRESSURE_WEAR_STATE";
                case DeviceEventType.User: return "USER";
                case DeviceEventType.Exercise: return "EXERCISE";
                case DeviceEventType.Activity: return "ACTIVITY";
                case DeviceEventType.Ecg: return "ECG";
                case DeviceEventType.Sleep: return "SLEEP";
                default: return null;
            }
        }

        private static string ReadStringProperty(AndroidJavaObject source, string property)
        {
            if (source == null)
                return "";

            try
            {
                return source.Get<string>(property) ?? "";
            }
            catch (Exception)
            {
                return "";
            }
        }

        private void ReportError(AidlabAPI.AidlabErrorCode code, string message)
        {
            lastError = message ?? "";
            status = "Error";
            owner.ReportError(new AidlabError(code, lastError));
        }

        private static ulong ToUInt64Bits(long value)
        {
            return unchecked((ulong)value);
        }

        private static int EnumValue(AndroidJavaObject value, int fallback)
        {
            if (value == null)
                return fallback;

            try
            {
                return value.Get<int>("value");
            }
            catch (Exception)
            {
                try
                {
                    return value.Call<int>("getValue");
                }
                catch (Exception)
                {
                    return fallback;
                }
            }
        }

        // A rejection keeps the reason of the Java ProcessRejectedException, as on the other platforms.
        private static Exception CommandError(AndroidJavaObject error)
        {
            string message = error.Call<string>("getMessage") ?? error.Call<string>("toString");
            string className;
            using (AndroidJavaObject javaClass = error.Call<AndroidJavaObject>("getClass"))
                className = javaClass.Call<string>("getName");
            if (className != "com.aidlab.sdk.ProcessRejectedException")
                return new InvalidOperationException(message);
            RejectionReason reason;
            using (AndroidJavaObject value = error.Call<AndroidJavaObject>("getReason"))
                reason = (RejectionReason)EnumValue(value, (int)RejectionReason.Unknown);
            return new ProcessRejectedException(reason, message);
        }

        // One scan serves every backend: Android stops delivering an app's scan results after about five scan starts in
        // 30 s, which a scan per backend and its reconnections would exceed. The scan runs while any backend waits for
        // a device and hands each discovered device to the first waiting backend that accepts it, unless another
        // instance holds it. It runs on the Unity main thread; the Android callbacks are queued to it.
        private static class SharedScan
        {
            // A scan fails at once while Bluetooth is off, so the waiting backends would otherwise restart it and report
            // the failure every frame.
            private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(2);

            // In the order the backends started waiting.
            private static readonly List<AndroidAidlabBackend> waiting = new List<AndroidAidlabBackend>();
            // Created for the first scan and kept for the process; the scan stops when no backend waits.
            private static AndroidJavaObject manager;
            private static bool scanning;
            private static DateTime nextScanAt = DateTime.MinValue;
            // Set once the app asked; a denial keeps it, so that the dialog does not reopen every frame, until a new
            // target name or a shutdown asks again. A grant, in the dialog or later in the system settings, starts the scan.
            private static bool permissionRequestIssued;

            internal static void Wait(AndroidAidlabBackend backend)
            {
                if (!waiting.Contains(backend))
                {
                    waiting.Add(backend);
                    if (scanning)
                        backend.OnScanning();
                }

                if (scanning || DateTime.UtcNow < nextScanAt)
                    return;

                if (!HasBluetoothPermissions())
                {
                    backend.status = "WaitingForPermissions";
                    RequestBluetoothPermissions();
                    return;
                }

                manager = manager ?? CreateManager();
                scanning = true;
                manager.Call("scan");
                foreach (AndroidAidlabBackend each in waiting)
                    each.OnScanning();
            }

            internal static void Leave(AndroidAidlabBackend backend)
            {
                if (!waiting.Remove(backend) || waiting.Count > 0 || !scanning)
                    return;

                scanning = false;
                manager.Call("stopScan");
            }

            internal static void AllowPermissionRequest()
            {
                permissionRequestIssued = false;
            }

            private static AndroidJavaObject CreateManager()
            {
                using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
                    return new AndroidJavaObject("com.aidlab.sdk.AidlabManager", currentActivity, new ScanDelegateProxy());
            }

            private static void OnDiscovered(AndroidJavaObject device)
            {
                string name = device.Call<string>("name") ?? "";
                string address = device.Call<string>("address");
                AndroidAidlabBackend backend = waiting.Find(candidate => candidate.Accepts(name, address));
                if (backend == null || !AidlabSDK.TryHoldDevice(address))
                {
                    device.Dispose();
                    return;
                }

                Leave(backend);
                backend.Connect(device, address);
            }

            private static void OnScanFailed(int errorCode)
            {
                // The failure of a scan stopped meanwhile concerns no backend.
                if (!scanning)
                    return;

                scanning = false;
                nextScanAt = DateTime.UtcNow + RetryDelay;
                // The error reaches the app, which may shut a backend down and so change the list.
                foreach (AndroidAidlabBackend backend in waiting.ToArray())
                    backend.ReportError(AidlabAPI.AidlabErrorCode.Transport, $"Android BLE scan failed (code={errorCode})");
            }

            private static bool HasBluetoothPermissions()
            {
                return Permission.HasUserAuthorizedPermission(BluetoothScanPermission) &&
                       Permission.HasUserAuthorizedPermission(BluetoothConnectPermission);
            }

            // One request for both and for every backend: Android drops a second request while the dialog of the first
            // is open.
            private static void RequestBluetoothPermissions()
            {
                if (permissionRequestIssued)
                    return;

                permissionRequestIssued = true;
                var callbacks = new PermissionCallbacks();
                callbacks.PermissionDenied += OnBluetoothPermissionDenied;
                callbacks.PermissionDeniedAndDontAskAgain += OnBluetoothPermissionDenied;
                Permission.RequestUserPermissions(new[] { BluetoothScanPermission, BluetoothConnectPermission }, callbacks);
            }

            private static void OnBluetoothPermissionDenied(string permission)
            {
                AidlabSDK.EnqueueMainThreadEvent(() =>
                {
                    foreach (AndroidAidlabBackend backend in waiting.ToArray())
                        backend.ReportError(AidlabAPI.AidlabErrorCode.Transport, $"Bluetooth permission denied: {permission}");
                });
            }

            private sealed class ScanDelegateProxy : AndroidJavaProxy
            {
                internal ScanDelegateProxy()
                    : base("com.aidlab.sdk.AidlabManagerDelegate")
                {
                }

                // Wait and Leave track the scan where they start and stop it.
                void onDeviceScanStarted() { }
                void onDeviceScanStopped() { }
                void onDeviceScanFailed(int errorCode) => AidlabSDK.EnqueueMainThreadEvent(() => OnScanFailed(errorCode));
                void didDiscover(AndroidJavaObject device, int rssi) =>
                    AidlabSDK.EnqueueMainThreadEvent(() => OnDiscovered(device));
            }
        }

        // A connection to one held device. Android ends every connection with exactly one report, also one that the
        // backend abandoned: the connect error before didConnect, didDisconnect after it. Only that report releases the
        // device, because the Android SDK refuses a second Device on an address while the first is connected.
        private sealed class Session
        {
            internal readonly AndroidJavaObject Device;
            internal readonly string Address;

            internal Session(AndroidJavaObject device, string address)
            {
                Device = device;
                Address = address;
            }

            internal void End()
            {
                AidlabSDK.ReleaseDevice(Address);
                Device.Dispose();
            }
        }

        // A proxy whose callbacks keep none of the Java objects they receive. Unity leaves the arguments of a proxy
        // call to the garbage collector, and each holds a JNI global reference until it is finalized: at 250 samples a
        // second from every device they could fill ART's table of 51200 global references, which aborts the app.
        private abstract class CallbackProxy : AndroidJavaProxy
        {
            protected CallbackProxy(string javaInterface)
                : base(javaInterface)
            {
            }

            public override AndroidJavaObject Invoke(string methodName, object[] args)
            {
                try
                {
                    return base.Invoke(methodName, args);
                }
                finally
                {
                    foreach (object arg in args)
                        (arg as AndroidJavaObject)?.Dispose();
                }
            }
        }

        private sealed class CommandCallbackProxy : CallbackProxy
        {
            // Completed on an Android thread, where the continuations of the caller must not run.
            private readonly TaskCompletionSource<int?> completion =
                new TaskCompletionSource<int?>(TaskCreationOptions.RunContinuationsAsynchronously);
            private readonly Action<CommandCallbackProxy> onCompleted;

            internal CommandCallbackProxy(Action<CommandCallbackProxy> onCompleted)
                : base("com.aidlab.sdk.CommandCallback")
            {
                this.onCompleted = onCompleted;
            }

            internal Task<int?> Task => completion.Task;

            // Unity unboxes a java.lang.Integer PID to int and passes null as an AndroidJavaObject.
            public void onResult(int pid) => Complete(pid);

            public void onResult(AndroidJavaObject pid) => Complete(null);

            private void Complete(int? pid)
            {
                completion.TrySetResult(pid);
                onCompleted?.Invoke(this);
            }

            public void onError(AndroidJavaObject error) => Fail(CommandError(error));

            internal void Fail(Exception exception)
            {
                completion.TrySetException(exception);
                onCompleted?.Invoke(this);
            }
        }

        private sealed class ConnectCallbackProxy : CallbackProxy
        {
            private readonly AndroidAidlabBackend backend;
            private readonly Session session;

            internal ConnectCallbackProxy(AndroidAidlabBackend backend, Session session)
                : base("com.aidlab.sdk.CommandCallback")
            {
                this.backend = backend;
                this.session = session;
            }

            // Success is reported through didConnect. Unity unboxes a java.lang.Integer PID to int and passes null as
            // an AndroidJavaObject.
            public void onResult(int pid) { }

            public void onResult(AndroidJavaObject pid) { }

            public void onError(AndroidJavaObject error)
            {
                string message = CommandError(error).Message;
                AidlabSDK.EnqueueMainThreadEvent(() => backend.OnConnectFailed(session, message));
            }
        }

        private sealed class DeviceDelegateProxy : CallbackProxy
        {
            private readonly AndroidAidlabBackend backend;
            private readonly Session session;

            internal DeviceDelegateProxy(AndroidAidlabBackend backend, Session session)
                : base("com.aidlab.sdk.DeviceDelegate")
            {
                this.backend = backend;
                this.session = session;
            }

            private AidlabDelegate Live => backend.owner.Delegate;
            private AidlabSyncDelegate Sync => backend.owner.SyncDelegate;

            void didConnect(AndroidJavaObject device) =>
                AidlabSDK.EnqueueMainThreadEvent(() => backend.OnConnected(session));

            void didDisconnect(AndroidJavaObject device, AndroidJavaObject reason) =>
                AidlabSDK.EnqueueMainThreadEvent(() => backend.OnDisconnected(session));

            void didReceiveECG(AndroidJavaObject device, long timestamp, float value)
            {
                backend.owner.AndroidDidReceiveData();
                Live.DidReceiveECG(ToUInt64Bits(timestamp), value);
            }

            void didReceiveRespiration(AndroidJavaObject device, long timestamp, float value)
            {
                backend.owner.AndroidDidReceiveData();
                Live.DidReceiveRespiration(ToUInt64Bits(timestamp), value);
            }

            void didReceiveRespirationRate(AndroidJavaObject device, long timestamp, int value)
            {
                backend.owner.AndroidDidReceiveData();
                Live.DidReceiveRespirationRate(ToUInt64Bits(timestamp), unchecked((uint)value));
            }

            void didReceiveBatteryLevel(AndroidJavaObject device, int value) =>
                Live.DidReceiveBatteryLevel(value);

            void didReceiveSkinTemperature(AndroidJavaObject device, long timestamp, float value)
            {
                backend.owner.AndroidDidReceiveData();
                Live.DidReceiveSkinTemperature(ToUInt64Bits(timestamp), value);
            }

            void didReceiveAccelerometer(AndroidJavaObject device, long timestamp, float x, float y, float z) =>
                Live.DidReceiveAccelerometer(ToUInt64Bits(timestamp), x, y, z);

            void didReceiveGyroscope(AndroidJavaObject device, long timestamp, float x, float y, float z) =>
                Live.DidReceiveGyroscope(ToUInt64Bits(timestamp), x, y, z);

            void didReceiveMagnetometer(AndroidJavaObject device, long timestamp, float x, float y, float z) =>
                Live.DidReceiveMagnetometer(ToUInt64Bits(timestamp), x, y, z);

            void didReceiveQuaternion(AndroidJavaObject device, long timestamp, float w, float x, float y, float z) =>
                Live.DidReceiveQuaternion(ToUInt64Bits(timestamp), w, x, y, z);

            void didReceiveOrientation(AndroidJavaObject device, long timestamp, float roll, float pitch, float yaw) =>
                Live.DidReceiveOrientation(ToUInt64Bits(timestamp), roll, pitch, yaw);

            void didReceiveEDA(AndroidJavaObject device, long timestamp, float value) =>
                Live.DidReceiveEda(ToUInt64Bits(timestamp), value);

            void didReceiveGPS(
                AndroidJavaObject device,
                long timestamp,
                double latitude,
                double longitude,
                double altitude,
                float speed,
                float heading,
                float hdop) =>
                Live.DidReceiveGps(
                    ToUInt64Bits(timestamp),
                    (float)latitude,
                    (float)longitude,
                    (float)altitude,
                    speed,
                    heading,
                    hdop
                );

            void didReceiveBodyPosition(AndroidJavaObject device, long timestamp, AndroidJavaObject value) =>
                Live.DidReceiveBodyPosition(
                    ToUInt64Bits(timestamp),
                    (BodyPosition)EnumValue(value, (int)BodyPosition.Undefined)
                );

            void didReceiveSteps(AndroidJavaObject device, long timestamp, long value) =>
                Live.DidReceiveSteps(ToUInt64Bits(timestamp), ToUInt64Bits(value));

            void didReceiveHeartRate(AndroidJavaObject device, long timestamp, int value) =>
                Live.DidReceiveHeartRate(ToUInt64Bits(timestamp), value);

            void didReceiveRr(AndroidJavaObject device, long timestamp, int value) =>
                Live.DidReceiveRr(ToUInt64Bits(timestamp), value);

            void didReceivePressure(AndroidJavaObject device, long timestamp, int value) =>
                Live.DidReceivePressure(ToUInt64Bits(timestamp), value);

            void didReceiveEvent(AndroidJavaObject device, AndroidJavaObject deviceEvent)
            {
                DeviceEvent parsed = ParseEvent(deviceEvent);
                if (parsed != null)
                    Live.DidReceiveEvent(parsed);
            }

            void didReceiveSoundVolume(AndroidJavaObject device, long timestamp, int value) =>
                Live.DidReceiveSoundVolume(ToUInt64Bits(timestamp), unchecked((ushort)value));

            void didReceiveSignalQuality(AndroidJavaObject device, long timestamp, int value) =>
                Live.DidReceiveSignalQuality(ToUInt64Bits(timestamp), unchecked((byte)value));

            void syncStateDidChange(AndroidJavaObject device, AndroidJavaObject value) =>
                Sync.SyncStateDidChange(
                    (SyncState)EnumValue(value, (int)SyncState.Unavailable)
                );

            void didReceiveUnsynchronizedSize(AndroidJavaObject device, long size, float bytesPerSecond) =>
                Sync.DidReceiveUnsynchronizedSize(unchecked((uint)size), bytesPerSecond);

            void didReceivePastECG(AndroidJavaObject device, long timestamp, float value) =>
                Sync.DidReceivePastEcg(ToUInt64Bits(timestamp), value);

            void didReceivePastRespiration(AndroidJavaObject device, long timestamp, float value) =>
                Sync.DidReceivePastRespiration(ToUInt64Bits(timestamp), value);

            void didReceivePastSkinTemperature(AndroidJavaObject device, long timestamp, float value) =>
                Sync.DidReceivePastTemperature(ToUInt64Bits(timestamp), value);

            void didReceivePastHeartRate(AndroidJavaObject device, long timestamp, int value) =>
                Sync.DidReceivePastHeartRate(ToUInt64Bits(timestamp), value);

            void didReceivePastRr(AndroidJavaObject device, long timestamp, int value) =>
                Sync.DidReceivePastRr(ToUInt64Bits(timestamp), value);

            void didReceivePastRespirationRate(AndroidJavaObject device, long timestamp, int value) =>
                Sync.DidReceivePastRespirationRate(ToUInt64Bits(timestamp), unchecked((uint)value));

            void didReceivePastSteps(AndroidJavaObject device, long timestamp, long value) =>
                Sync.DidReceivePastSteps(ToUInt64Bits(timestamp), ToUInt64Bits(value));

            void didReceivePastAccelerometer(AndroidJavaObject device, long timestamp, float x, float y, float z) =>
                Sync.DidReceivePastAccelerometer(ToUInt64Bits(timestamp), x, y, z);

            void didReceivePastGyroscope(AndroidJavaObject device, long timestamp, float x, float y, float z) =>
                Sync.DidReceivePastGyroscope(ToUInt64Bits(timestamp), x, y, z);

            void didReceivePastMagnetometer(AndroidJavaObject device, long timestamp, float x, float y, float z) =>
                Sync.DidReceivePastMagnetometer(ToUInt64Bits(timestamp), x, y, z);

            void didReceivePastQuaternion(AndroidJavaObject device, long timestamp, float w, float x, float y, float z) =>
                Sync.DidReceivePastQuaternion(ToUInt64Bits(timestamp), w, x, y, z);

            void didReceivePastOrientation(
                AndroidJavaObject device,
                long timestamp,
                float roll,
                float pitch,
                float yaw) =>
                Sync.DidReceivePastOrientation(
                    ToUInt64Bits(timestamp),
                    roll,
                    pitch,
                    yaw
                );

            void didReceivePastEDA(AndroidJavaObject device, long timestamp, float value) =>
                Sync.DidReceivePastEda(ToUInt64Bits(timestamp), value);

            void didReceivePastGPS(
                AndroidJavaObject device,
                long timestamp,
                double latitude,
                double longitude,
                double altitude,
                float speed,
                float heading,
                float hdop) =>
                Sync.DidReceivePastGps(
                    ToUInt64Bits(timestamp),
                    (float)latitude,
                    (float)longitude,
                    (float)altitude,
                    speed,
                    heading,
                    hdop
                );

            void didReceivePastBodyPosition(AndroidJavaObject device, long timestamp, AndroidJavaObject value) =>
                Sync.DidReceivePastBodyPosition(
                    ToUInt64Bits(timestamp),
                    (BodyPosition)EnumValue(value, (int)BodyPosition.Undefined)
                );

            void didReceivePastSoundVolume(AndroidJavaObject device, long timestamp, int value) =>
                Sync.DidReceivePastSoundVolume(ToUInt64Bits(timestamp), unchecked((ushort)value));

            void didReceivePastPressure(AndroidJavaObject device, long timestamp, int value) =>
                Sync.DidReceivePastPressure(ToUInt64Bits(timestamp), value);

            void didReceivePastSignalQuality(AndroidJavaObject device, long timestamp, int value) =>
                Sync.DidReceivePastSignalQuality(ToUInt64Bits(timestamp), unchecked((byte)value));

            void didReceiveError(AndroidJavaObject device, AndroidJavaObject error) =>
                backend.owner.ReportError(ParseError(error));

            // Unity unboxes a Java byte[] to sbyte[]; a method that takes another type is never called.
            void didReceiveProcessOutput(
                AndroidJavaObject device,
                int pid,
                sbyte[] payload,
                long options) =>
                backend.owner.AndroidDidReceiveProcessOutput(
                    pid,
                    ConvertByteArray(payload),
                    unchecked((ulong)options)
                );

            void didReceiveProcessError(
                AndroidJavaObject device,
                int pid,
                sbyte[] payload,
                long options) =>
                backend.owner.AndroidDidReceiveProcessError(
                    pid,
                    ConvertByteArray(payload),
                    unchecked((ulong)options)
                );

            // Unity unboxes a java.lang.Integer exit status to int and passes null as an AndroidJavaObject.
            void processDidExit(AndroidJavaObject device, int pid, int exitStatus) =>
                backend.owner.AndroidProcessDidExit(pid, exitStatus);

            void processDidExit(AndroidJavaObject device, int pid, AndroidJavaObject exitStatus) =>
                backend.owner.AndroidProcessDidExit(pid, null);

            private static byte[] ConvertByteArray(sbyte[] payload)
            {
                var bytes = new byte[payload.Length];
                Buffer.BlockCopy(payload, 0, bytes, 0, payload.Length);
                return bytes;
            }

            // Maps the com.aidlab.sdk.DeviceEvent data classes. A newer Android SDK may add event types; they are not
            // delivered.
            private static DeviceEvent ParseEvent(AndroidJavaObject deviceEvent)
            {
                ulong timestamp = ToUInt64Bits(deviceEvent.Call<long>("getTimestamp"));
                bool isPast = deviceEvent.Call<bool>("isPast");
                // Nullable Kotlin properties: java.lang.Long and java.lang.Float, null while a period lasts or when
                // the detector reports no confidence.
                ulong? end;
                using (AndroidJavaObject value = deviceEvent.Call<AndroidJavaObject>("getEndTimestamp"))
                    end = value == null ? (ulong?)null : ToUInt64Bits(value.Call<long>("longValue"));
                float? confidence;
                using (AndroidJavaObject value = deviceEvent.Call<AndroidJavaObject>("getConfidence"))
                    confidence = value == null ? (float?)null : value.Call<float>("floatValue");
                string className;
                using (AndroidJavaObject javaClass = deviceEvent.Call<AndroidJavaObject>("getClass"))
                    className = javaClass.Call<string>("getName");

                switch (className)
                {
                    case "com.aidlab.sdk.WearStateEvent":
                        return new WearStateEvent(
                            timestamp,
                            end,
                            confidence,
                            isPast,
                            (WearState)EnumProperty(deviceEvent, "getWearState", (int)WearState.Unknown)
                        );
                    case "com.aidlab.sdk.PressureWearStateEvent":
                        return new PressureWearStateEvent(
                            timestamp,
                            end,
                            confidence,
                            isPast,
                            (WearState)EnumProperty(deviceEvent, "getWearState", (int)WearState.Unknown)
                        );
                    case "com.aidlab.sdk.UserEvent":
                        return new UserEvent(timestamp, end, confidence, isPast);
                    case "com.aidlab.sdk.ExerciseEvent":
                        return new ExerciseEvent(
                            timestamp,
                            end,
                            confidence,
                            isPast,
                            (Exercise)EnumProperty(deviceEvent, "getExercise", (int)Exercise.None)
                        );
                    case "com.aidlab.sdk.ActivityEvent":
                        return new ActivityEvent(
                            timestamp,
                            end,
                            confidence,
                            isPast,
                            (ActivityType)EnumProperty(deviceEvent, "getActivity", (int)ActivityType.Unspecific)
                        );
                    case "com.aidlab.sdk.EcgEvent":
                        return new EcgEvent(
                            timestamp,
                            end,
                            confidence,
                            isPast,
                            deviceEvent.Call<int>("getAnntyp"),
                            deviceEvent.Call<int>("getSubtyp"),
                            deviceEvent.Call<string>("getAux"),
                            EnumNameProperty<EcgRhythm>(deviceEvent, "getRhythm"),
                            deviceEvent.Call<string>("getModelVersion")
                        );
                    case "com.aidlab.sdk.SleepEvent":
                        return new SleepEvent(
                            timestamp,
                            end,
                            confidence,
                            isPast,
                            EnumNameProperty<SleepPeriod>(deviceEvent, "getPeriod") ?? SleepPeriod.Unknown,
                            deviceEvent.Call<string>("getModelVersion")
                        );
                    default:
                        return null;
                }
            }

            private static int EnumProperty(AndroidJavaObject source, string getter, int fallback)
            {
                using (AndroidJavaObject value = source.Call<AndroidJavaObject>(getter))
                    return EnumValue(value, fallback);
            }

            // Kotlin enum constants are the C# names in SCREAMING_SNAKE_CASE, e.g. ATRIAL_FIBRILLATION. Null when the
            // property is null or its constant is unknown.
            private static T? EnumNameProperty<T>(AndroidJavaObject source, string getter) where T : struct, Enum
            {
                using (AndroidJavaObject value = source.Call<AndroidJavaObject>(getter))
                {
                    string name = value?.Call<string>("name")?.Replace("_", "");
                    return name != null && Enum.TryParse(name, true, out T result) ? result : (T?)null;
                }
            }

            private static AidlabError ParseError(AndroidJavaObject error)
            {
                if (error == null)
                    return new AidlabError(AidlabAPI.AidlabErrorCode.Sdk, "");

                string message;
                try
                {
                    message = error.Call<string>("getMessage") ?? "";
                }
                catch (Exception)
                {
                    message = error.Call<string>("toString") ?? "";
                }

                int rawCode = (int)AidlabAPI.AidlabErrorCode.Sdk;
                try
                {
                    using (AndroidJavaObject code = error.Call<AndroidJavaObject>("getCode"))
                        rawCode = code?.Call<int>("getValue") ?? rawCode;
                }
                catch (Exception)
                {
                    // Unknown Android error code is represented as a generic SDK error.
                }

                var parsedCode = Enum.IsDefined(typeof(AidlabAPI.AidlabErrorCode), rawCode)
                    ? (AidlabAPI.AidlabErrorCode)rawCode
                    : AidlabAPI.AidlabErrorCode.Sdk;
                return new AidlabError(parsedCode, message);
            }
        }
    }
}
#endif
