package com.abbidot.tracker.util

import android.content.Context
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.util.bluetooth.SRBleCmdUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.clj.fastble.utils.HexUtil
import com.easysocket.EasySocket
import com.easysocket.config.EasySocketOptions
import com.easysocket.entity.OriginReadData
import com.easysocket.entity.SocketAddress
import com.easysocket.interfaces.conn.ISocketActionListener
import java.util.Timer
import kotlin.concurrent.timerTask


/**
 *Created  by .yzq on 2025/4/18/018.
 * @link
 * @description:
 */
class SocketUtilManageV2 {

    private var mNeedSendMessage = byteArrayOf()
    private val mTimer = Timer()
    private var mMac = ""

    @Synchronized
    fun initEasySocket(context: Context, mac: String, data: ByteArray) {
        val data1 = SRBleCmdUtil.instance.byteToInt(data[1])
        val data2 = SRBleCmdUtil.instance.byteToInt(data[2])
        val data3 = SRBleCmdUtil.instance.byteToInt(data[3])
        val data4 = SRBleCmdUtil.instance.byteToInt(data[4])
        val ip = "$data1.$data2.$data3.$data4"
        val port = SRBleCmdUtil.instance.byte2ArrayToInt(data.sliceArray(5..6))
        val socketAddress = "$ip:$port"
        LogUtil.e(socketAddress)
        mMac = mac
        mNeedSendMessage = data.sliceArray(8..data.size - 2)
        initEasySocket(context, ip, port)
    }

    /**
     * 初始化EasySocket
     */
    private fun initEasySocket(context: Context, ip: String, port: Int) {
        //socket配置
        val options = EasySocketOptions.Builder().setSocketAddress(SocketAddress(ip, port))
            .setMaxWriteBytes(300)
            // 强烈建议定义一个消息协议，方便解决 socket黏包、分包的问题
            // .setReaderProtocol(new DefaultMessageProtocol()) // 默认的消息协议
            .build()
        //初始化EasySocket
        EasySocket.getInstance().createConnection(options, context).setDebug(AppUtils.isDebug())
//        EasySocket.getInstance().createSpecifyConnection(options, context)

        //监听socket相关行为
        EasySocket.getInstance().subscribeSocketAction(object : ISocketActionListener {
            override fun onSocketConnSuccess(socketAddress: SocketAddress?) {
                LogUtil.e("socket连接成功")
                //发送
                mTimer.schedule(timerTask {
                    LogUtil.e("发送")
                    EasySocket.getInstance().upMessage(mNeedSendMessage)
                }, 500)
            }

            override fun onSocketConnFail(socketAddress: SocketAddress?, isNeedReconnect: Boolean) {
                LogUtil.e("socket连接失败,是否需要重连:$isNeedReconnect")
                replyBleResult(1, null)
            }

            override fun onSocketDisconnect(
                socketAddress: SocketAddress?, isNeedReconnect: Boolean
            ) {
                LogUtil.e("socket断开连接,是否需要重连:$isNeedReconnect")
            }

            override fun onSocketResponse(
                socketAddress: SocketAddress?, originReadData: OriginReadData?
            ) {
                LogUtil.d("socket监听器收到对象数据=" + originReadData?.bodyString)
            }

            override fun onSocketResponse(socketAddress: SocketAddress?, readData: String?) {
                LogUtil.d("socket监听器收到字符串数据=$readData")
            }

            override fun onSocketResponse(socketAddress: SocketAddress?, readData: ByteArray?) {
                val data = HexUtil.formatHexString(readData, true)
                LogUtil.e("socket监听器收到字节数组数据=$data")
                readData?.apply {
                    if (size > 16 && this[15] == (0x94).toByte()) {
                        replyBleResult(0, this)
                    }
                }
            }
        })
    }

    private fun replyBleResult(result: Int, data: ByteArray?) {
        SRBleUtil.instance.getConnectMacDevice(mMac)?.let {
            SRBleUtil.instance.writeData(
                it.bleDevice, SRBleCmdUtil.instance.setProxy(result, data)
            )
        }
        destroy()
    }

    private fun destroy() {
        try {
            //destroyConnection()代表销毁整个连接状态，跟disconnect()不一样，如果此时要进行socket连接需要重新创建一个连接
            EasySocket.getInstance().destroyConnection()
            //注销监听socket相关行为
            EasySocket.getInstance().defOptions.reconnectionManager.detach()
            LogUtil.e("socket销毁连接")
        } catch (e: Exception) {
            LogUtil.e("socket销毁连接异常：${e.message}")
        }
    }
}