package com.common.bluetooth.service.ble;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;

import com.common.bluetooth.service.BluetoothCommon;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 蓝牙操作管理类
 *
 * @author wangym
 * @since 2021-10-19
 */
public class BluetoothLeClient extends BluetoothCommon {
    @SuppressLint("StaticFieldLeak")
    private static volatile BluetoothLeClient mInstance;

    private final static String TAG = "BluetoothLeClient";
    private final Context mContext;
    private static Handler mBluetoothWorker;

    private final Map<String, BluetoothLeConnector> mGattConnectorMap
            = new ConcurrentHashMap<>();

    private BluetoothLeClient(Context context) {
        super(context.getApplicationContext());
        mContext = context.getApplicationContext();
        HandlerThread thread = new HandlerThread("bluetooth client worker");
        thread.start();
        mBluetoothWorker = new Handler(thread.getLooper());
    }

    public static BluetoothLeClient getInstance(Context context) {
        if (mInstance == null) {
            synchronized (BluetoothLeClient.class) {
                if (mInstance == null) {
                    mInstance = new BluetoothLeClient(context);
                }
            }
        }

        return mInstance;
    }

    public BluetoothLeConnector getBluetoothLeConnector(String mac) {
        BluetoothLeConnector result;
        if ((result = mGattConnectorMap.get(mac)) != null) {
            return result;
        }

        result = new BluetoothLeConnector(mContext, getMBluetoothAdapter(), mac, mBluetoothWorker);
        mGattConnectorMap.put(mac, result);
        return result;
    }

    public void cleanConnector(String mac) {
        BluetoothLeConnector result;
        if ((result = mGattConnectorMap.get(mac)) != null) {
            mGattConnectorMap.remove(mac);
            result.disconnect();
            result.setOnDataAvailableListener(null);
        }
    }

    /**
     * 在不在需要连接蓝牙设备的时候，
     * 或者生命周期暂停的时候调用这一个方法
     */
    public void cleanAllConnector() {
        for (String mac : mGattConnectorMap.keySet()) {
            cleanConnector(mac);
        }
    }
}
