using Android.Bluetooth;
using Android.Bluetooth.LE;
using Android.Content;
using Android.OS;
using System;
using System.Collections.Generic;

namespace MyLibrary.Bluetooth
{
    public class BLEScanner
    {
        private BluetoothManager _bluetoothManager;
        private BluetoothAdapter _bluetoothAdapter;
        private BluetoothLeScanner _bluetoothLeScanner;
        private ScanCallback _scanCallback;

        public BLEScanner(Context context)
        {
            _bluetoothManager = (BluetoothManager)context.GetSystemService(Context.BluetoothService);
            _bluetoothAdapter = _bluetoothManager.Adapter;
            _bluetoothLeScanner = _bluetoothAdapter?.BluetoothLeScanner;

            if (_bluetoothLeScanner == null)
            {
                throw new Exception("Bluetooth LE Scanner is not available.");
            }
        }
        
        /*
         var bleScanner = new BLEScanner(Android.App.Application.Context);

bleScanner.StartScan(
    
);

// Stop the scan after 10 seconds
Task.Delay(10000).ContinueWith(_ => bleScanner.StopScan());

         */

        public void StartScan(Action<ScanResult> onDeviceFound, Action onScanStopped = null)
        {
            _scanCallback = new CustomScanCallback(onDeviceFound, onScanStopped);
            _bluetoothLeScanner.StartScan(_scanCallback);
        }

        public void StopScan()
        {
            _bluetoothLeScanner?.StopScan(_scanCallback);
        }

        private class CustomScanCallback : ScanCallback
        {
            private readonly Action<ScanResult> _onDeviceFound;
            private readonly Action _onScanStopped;

            public CustomScanCallback(Action<ScanResult> onDeviceFound, Action onScanStopped)
            {
                _onDeviceFound = onDeviceFound;
                _onScanStopped = onScanStopped;
            }

            public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
            {
                base.OnScanResult(callbackType, result);
                _onDeviceFound?.Invoke(result);
            }

            public override void OnScanFailed(ScanFailure errorCode)
            {
                base.OnScanFailed(errorCode);
                _onScanStopped?.Invoke();
                throw new Exception($"Scan failed with error code: {errorCode}");
            }
        }
    }
}
