package cgmblelib.ble.scancallback;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;

import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙搜索类
 * Created by minyuchun on 2019/12/23.
 *
 * @author minyuchun
 */

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class BleScanCallback extends ScanCallback {
    /***
     *  搜素设置
     */
    private ScanSettings mScanSettings;
    /**
     * 搜索过滤器
     */
    private List<ScanFilter> mScanFilters;

    @SuppressLint("MissingPermission")
    public boolean startScan(@NonNull BluetoothAdapter adapter) {
        if (adapter.isEnabled()) {
            adapter.getBluetoothLeScanner().startScan(getScanFilters(), getScanSettings(), this);
        }
        return true;
    }

    /**
     * stop to scan CGM device
     *
     * @param adapter BluetoothAdapter from phone
     */
    @SuppressLint("MissingPermission")
    public void stopLeScan(BluetoothAdapter adapter) {
        if (adapter.isEnabled()) {
            adapter.getBluetoothLeScanner().stopScan(this);
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        super.onScanResult(callbackType, result);
        ManageScanCallback.getInstance().onScanResult(
                callbackType,
                result.getDevice(),
                result.getScanRecord() != null ? result.getScanRecord().getBytes() : null,
                result.getRssi()
        );
        //表示远程设备已绑定，远程设备本地存储共享连接的密钥，因此可以对通信进行身份验证和加密
//        result.getDevice().getBondState()  == BluetoothDevice.BOND_BONDED; 12
        //表示远程设备未绑定，没有共享链接密钥，因此通信（如果允许的话）将是未经身份验证和未加密的
//        result.getDevice().getBondState()  == BluetoothDevice.BOND_NONE; 10
        //正在绑定
//        result.getDevice().getBondState()  == BluetoothDevice.BOND_BONDING; 11
    }


    @Override
    public void onScanFailed(int errorCode) {
        super.onScanFailed(errorCode);
        //扫描太频繁会返回ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED，表示app无法注册，无法开始扫描。
        ManageScanCallback.getInstance().onScanFailed(errorCode);
    }


    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        super.onBatchScanResults(results);
    }


    private ScanSettings getScanSettings() {
        if (mScanSettings == null) {
            ScanSettings.Builder builder = new ScanSettings.Builder()
                    //设置高功耗模式
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
            //android 6.0添加设置回调类型、匹配模式等
            //定义回调类型
            builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
            //设置蓝牙LE扫描滤波器硬件匹配的匹配模式
            builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
            mScanSettings = builder.build();
        }
        return mScanSettings;
    }

    /**
     * 获取扫描过滤器
     *
     * @return 返回过滤器
     */
    private List<ScanFilter> getScanFilters() {
        if (mScanFilters == null){
            mScanFilters = new ArrayList<>();
            ScanFilter scanFilter = new ScanFilter.Builder().build();
            mScanFilters.add(scanFilter);
        }
        return mScanFilters;
    }
}
