package com.common.bluetooth.service.bt

import android.bluetooth.BluetoothDevice
import com.common.bluetooth.BtConstants
import com.common.bluetooth.callback.BaseResultCallback
import com.common.bluetooth.interfaces.IBluetoothClient
import io.reactivex.rxjava3.core.Observable
import java.util.UUID

/**
 * 经典蓝牙适配器
 *
 * @author wangym
 * @since 2021-12-1
 */
class BluetoothClientClassicAdapter(private var mClient: BluetoothClassicClient) :
    IBluetoothClient {
    val TAG = "BluetoothClientAdapter"

    override fun search(millis: Long, cancel: Boolean): Observable<BluetoothDevice> {
        return Observable.create {
            mClient.getBluetoothSearcher().startScan(millis, null)
            it.onComplete()
        }
    }

    override fun stopSearch() {
        mClient.getBluetoothSearcher().stopScan()
    }

    override fun connect(mac: String): Observable<String> {
        return Observable.create {
            if (!mClient.isConnected((mac))) {
                mClient.connect(mac)
            }
            it.onNext(mac)
            it.onComplete()
        }
    }

    override fun disconnect(mac: String) {
        mClient.close()
    }

    override fun write(
        mac: String,
        service: UUID,
        characteristic: UUID,
        values: ByteArray
    ): Observable<String>? {
        return Observable.create {
            if (!mClient.isConnected((mac))) {
                mClient.sendMsg(values)
            }
            it.onNext(mac)
            it.onComplete()
        }
    }

    override fun checkBluetoothDevice(type: BtConstants.BLUETOOTH_TYPE): Boolean {
        return mClient.checkBtDevice(type)
    }

    override fun openBluetooth() {
        mClient.openBt()
    }

    override fun closeBluetooth(): Boolean {
        return mClient.closeBt()
    }

    override fun getBondedDevices(): Set<BluetoothDevice>? {
        return mClient.getBondedDevices()
    }

    override fun registerNotify(
        mac: String,
        service: UUID,
        characteristic: UUID,
        callback: BaseResultCallback<ByteArray>?
    ): Observable<String> {
        return Observable.create {}
    }

    override fun unRegisterNotify(
        mac: String,
        service: UUID,
        characteristic: UUID
    ): Observable<String>? {
        return null
    }

    override fun clean(mac: String) {
    }

    override fun cleanAll() {
    }
}