package com.xhly.manageapp.broadcastreceiver

import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent

class BLEStateReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        // 检测蓝牙状态的逻辑
        checkBLEState(context, intent)
    }

    /**
     * 检测蓝牙状态
     *
     * @param context
     * @param intent
     */
    @Synchronized
    private fun checkBLEState(context: Context, intent: Intent) {
        val BLEState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
        Log.i("执行监听", "--------蓝牙监听$BLEState")
        when (BLEState) {
            BluetoothAdapter.STATE_ON ->                 // 蓝牙已经打开
            {
              /*  Toast.makeText(context, "蓝牙打开", Toast.LENGTH_LONG).show()*/
                UIEvent(Const.BLUETOOTHOPEN).post()
            }

            BluetoothAdapter.STATE_TURNING_OFF ->                 // 蓝牙正在关闭
            {
               /* Toast.makeText(context, "蓝牙关闭", Toast.LENGTH_LONG).show()*/
            }
        }
    }

    companion object {
        private const val BLE_STATE_OFF = "android.bluetooth.BluetoothAdapter.STATE_OFF"
        private const val BLE_STATE_ON = "android.bluetooth.BluetoothAdapter.STATE_ON"
        private val receiver = BLEStateReceiver()

        /**
         * 注册
         *
         * @param context
         */
        fun register(context: Context?) {
            /*  IntentFilter filter = new IntentFilter();
        filter.setPriority(Integer.MAX_VALUE);
        // 监视蓝牙关闭和打开的状态
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BLE_STATE_OFF);
        filter.addAction(BLE_STATE_ON);
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        context.registerReceiver(receiver, filter);*/
        }

        /**
         * 注销
         *
         * @param context
         */
        fun unregister(context: Context?) {
            // context.unregisterReceiver(receiver);
        }
    }
}