package xn.hxp.blu

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.os.Handler
import android.widget.Toast
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import xn.hxp.blu.bean.IBluetoothCallback
import com.rc.core.util.Weak
import java.io.IOException
import java.io.InputStream
import java.io.PrintWriter
import java.util.UUID


/**
 * 蓝牙连接
 */
class BluetoothHelper(
    context: Context,
    private val iBluetoothCallback: IBluetoothCallback? = null,
) {
    private val mContext: Context? by Weak { context }
    private var mBluetoothAdapter: BluetoothAdapter? = null
    private var device: BluetoothDevice? = null
    val UUIDString = "00001101-0000-1000-8000-00805F9B34FB"
    private var mSocket: BluetoothSocket? = null
    private val lock = Any()
    private var mInputBluetooth: InputStream? = null
    private var out: PrintWriter? = null
    private val mHandler: Handler? = Handler()
    private var gotoLoginAct: Runnable? = null
    private var mAddress: String? = null

    fun onResume() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        //判断蓝牙设备是否已开起
        if (!mBluetoothAdapter!!.isEnabled) {
            LogUtils.i("=========不支持蓝牙")
            iBluetoothCallback?.onIsConnected("蓝牙未开启")
            return
        }
        iBluetoothCallback?.onReStart()
        val devices = mBluetoothAdapter!!.bondedDevices
        val iterator: Iterator<BluetoothDevice> = devices.iterator()
        while (iterator.hasNext()) {
            device = iterator.next()
        }
        val name = device?.name
        LogUtils.i("=========蓝牙已配置参数name$name")
//        if (name != null && name == "RS001") {
        if (name != null && name == "HF-18") {
//        if (name != null && name == "RS-001-BLE") {
            mAddress = device?.address
            LogUtils.i("=========蓝牙已配置参数$mAddress")
            val remoteDevice = mBluetoothAdapter!!.getRemoteDevice(mAddress)
            try {
                mSocket =
                    remoteDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUIDString))
                connect()
            } catch (e: Exception) {
                mSocket = null
                onCloses()
                Toast.makeText(ActivityUtils.getTopActivity(), "蓝牙1连接异常", Toast.LENGTH_SHORT).show()
            }
        } else {
            mSocket = null
            onCloses()
            iBluetoothCallback?.onIsConnected("蓝牙秤1连接失败$name")
        }

    }


    private fun connect() {

        gotoLoginAct = object : Runnable {
            override fun run() {
                try {
                    synchronized(lock) {
//                        if (mSocket!!.isConnected) {
//                            onCloses()
//                            iBluetoothCallback?.onIsConnected("蓝牙2秤连接失败")
//                            return
//                        } else {
//                            mSocket!!.connect() // 会阻塞线程，建议在子线程中进行
//                            iBluetoothCallback?.onBluetoothSocketBean(mSocket!!)
//                        }
                        mSocket!!.connect() // 会阻塞线程，建议在子线程中进行
//                        Thread.sleep(2000)
                        if (mSocket!!.isConnected) {
                            // 连接成功处理逻辑
                            iBluetoothCallback?.onBluetoothSocketBean(mSocket!!)
                        } else {
                            onCloses()
                            iBluetoothCallback?.onIsConnected("蓝牙秤连接失败")
                        }
                    }
                } catch (e: IOException) {
                    mSocket = null
                    mHandler!!.removeCallbacks(gotoLoginAct!!) //停止线程
                    mHandler!!.removeCallbacksAndMessages(null)
                    iBluetoothCallback?.onConnectError()
                    e.printStackTrace()
                    LogUtils.i("=========蓝牙3连接异常$e")
                }
            }
        }
        mHandler?.postDelayed(gotoLoginAct!!, 100)

    }

    //关闭所有资源
    fun onCloses() {
        if (mSocket != null) {
            mSocket!!.close()
            mHandler!!.removeCallbacks(gotoLoginAct!!) //停止线程
            mHandler!!.removeCallbacksAndMessages(null)
        }

    }
}