package com.xty.common.bracelet

import android.bluetooth.BluetoothAdapter
import androidx.core.app.ActivityCompat
import com.hjq.toast.ToastUtils
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.event.BlueToothConnectEvent
import com.xty.network.MyRetrofit
import com.yucheng.ycbtsdk.Constants
import com.yucheng.ycbtsdk.YCBTClient
import com.yucheng.ycbtsdk.bean.ScanDeviceBean
import org.greenrobot.eventbus.EventBus
import java.util.*


/**
 * 蓝牙连接状态帮助类
 */
object YCBBlueConnectHelper {

    private val blueAdapter by lazy { BluetoothAdapter.getDefaultAdapter() }
    private const val TAG = "BlueTooth"

    enum class BLEConnectState {
        DisConnect,//未连接
        Connecting,//连接中
        Connected,//已连接
    }

    //断开连接
    fun disconnect() {
        LogUtils.d(TAG, "disconnect")
        YCBTClient.disconnectBle()
    }


    /**
     * 连接蓝牙
     *
     * @param devMac 蓝牙mac地址
     * @param retryConnect 是否自动重连
     *
     */
    fun connectionBlueTooth(
        devMac: String,
        retryConnect: Boolean = false,
        isManual: Boolean = true,
        result: (code: BLEConnectState) -> Unit
    ) {

        val state = getBleNowStatus()

        if (devMac.isNullOrEmpty() || !BluetoothAdapter.checkBluetoothAddress(devMac)) {
            LogUtils.e(TAG, "蓝牙连接地址异常！！！$devMac")
            if (state != BLEConnectState.DisConnect){
                disconnect()
            }
            cancelTimer()
            result(BLEConnectState.DisConnect)
            return
        }

        if (!blueAdapter.isEnabled) {//手机蓝牙未开启
            LogUtils.e(TAG, "手机蓝牙未开启！！！")
            if (state != BLEConnectState.DisConnect){
                disconnect()
            }
            cancelTimer()
            result(BLEConnectState.DisConnect)
            return
        }

        if (MyRetrofit.get().BLUETOOTH_MAC.isNullOrEmpty() && !isManual){
            LogUtils.e(TAG, "解除绑定后自动重连请求结束！！！")
            if (state != BLEConnectState.DisConnect){
                disconnect()
            }
            cancelTimer()
            result(BLEConnectState.DisConnect)
            return
        }

        LogUtils.d(TAG, "手表蓝牙连接状态:$state;;; devMac:$devMac")
        when (state) {
            BLEConnectState.Connecting -> {
                result(BLEConnectState.Connecting)
            }

            BLEConnectState.Connected -> {
                cancelTimer()
                result(BLEConnectState.Connected)
            }

            BLEConnectState.DisConnect -> {
                LogUtils.d("开始连接蓝牙手表...")
                try {
                    YCBTClient.connectBle(devMac) { i ->
                        LogUtils.d("手表蓝牙连接ResultCode:$i")
                        var connectCode = BLEConnectState.DisConnect
                        var connectStatu = i == Constants.CODE.Code_OK
                        if (connectStatu) {
                            connectCode = BLEConnectState.Connected
                            cancelTimer()
                        } else {
                            if (retryConnect && MMkvHelper.contains(Const.Blue_Tooth)) {
                                retryConnectBlue(devMac)
                            }
                        }
                        result(connectCode)
                    }
                } catch (exception: Exception) {
                    LogUtils.e("蓝牙连接出错了。。。$exception")
                    ToastUtils.show("蓝牙连接出错:$exception")
                    result(BLEConnectState.DisConnect)
                }
            }
        }
    }


    /**
     * 尝试重新连接蓝牙
     *
     * 延时10秒执行
     */
    var timer: Timer? = null
    var retryTime: Int = 0
    const val MaxRetryTime: Int = 12//最多重试30次
    private fun retryConnectBlue(devMac: String) {

        LogUtils.d("retryConnectBlue devMac$devMac")

        if (timer != null){
            return
        }


        timer = Timer()

        timer!!.schedule(object : TimerTask() {
            override fun run() {

                LogUtils.d("Timer: Run!!!!")
                retryTime++
                if (retryTime > MaxRetryTime){//超过最大连接次数
                    retryTime = 0
                    cancelTimer()
                    return
                }

                if (!blueAdapter.isEnabled) {//手机蓝牙未开启
                    return
                }

                if (getBleNowStatus() == BLEConnectState.Connected) {//蓝牙已连接成功
                    cancelTimer()
                    return
                } else {
                    if (retryTime % 3 == 0) {//如果当前为未连接，并且retryTime取余为0则断开重连
                        disconnect()
                        return
                    }
                }

                LogUtils.d("retryConnect!!!")
                connectionBlueTooth(devMac, false, isManual = false) {
                    when (it) {
                        BLEConnectState.Connected -> {
                            cancelTimer()
                            EventBus.getDefault().post(BlueToothConnectEvent())
                        }
                        else -> {}
                    }
                }
            }

        }, 10000, 10000)

    }

    fun cancelTimer(){
        LogUtils.d("Timer: cancel!!!!")
        if (timer != null){
            timer!!.cancel()
            timer = null
        }
    }

    /**
     * 关闭蓝牙搜索
     */
    fun stopBlueSearch() {
        LogUtils.d(TAG, "stopBlueSearch")
        YCBTClient.stopScanBle()
    }


    /**
     * 搜索蓝牙
     */
    fun scanBlueTooth(result: (bean: ScanDeviceBean) -> Unit) {
        LogUtils.d(TAG, "scanBlueTooth")
        YCBTClient.startScanBle({ _, scanDeviceBean ->
            if (scanDeviceBean != null) {
                LogUtils.d(
                    "mac=${scanDeviceBean.deviceMac};name=${scanDeviceBean.deviceName} rssi= ${scanDeviceBean.deviceRssi}"
                )
                result.invoke(scanDeviceBean)
            }
        }, 10)
    }

    /**
     * 获取蓝牙状态
     * isToast  是否有弹出框
     */
    fun getBlueStatus(isToast: Boolean = true): Boolean {
        var status = YCBTClient.connectState()
        if (status == Constants.BLEState.ReadWriteOK) {
            return true
        }

        if (isToast) {
            ToastUtils.show("设备未连接")
        }
        return false
    }

    /**
     * 是否存在蓝牙设备
     */
    fun isBlueExits(): Boolean{
        var status = YCBTClient.connectState()
        LogUtils.d("isBlueExits:$status")
        if (status == Constants.BLEState.NotOpen || status == Constants.BLEState.Disconnect) {
            return false
        }

        return true
    }

    /**
     * 获取蓝牙当前状态
     */
    fun getBleNowStatus(): BLEConnectState {
        var status = YCBTClient.connectState()
        LogUtils.d(TAG, "手表蓝牙当前状态：$status")
        when (status) {
            Constants.BLEState.ReadWriteOK -> {
                return BLEConnectState.Connected
            }

            Constants.BLEState.Connecting,
            Constants.BLEState.Connected,
            Constants.BLEState.ServicesDiscovered,
            Constants.BLEState.CharacteristicNotification -> {
                return BLEConnectState.Connecting
            }

            Constants.BLEState.CharacteristicDiscovered->{
                return BLEConnectState.Connected
            }

            Constants.BLEState.TimeOut,
            Constants.BLEState.NotOpen,
            Constants.BLEState.Disconnect,
            Constants.BLEState.Disconnecting -> {
                return BLEConnectState.DisConnect
            }
        }
        return BLEConnectState.DisConnect
    }
}