package com.rgt.superr.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update

class VpnStatusListener(context: Context) {

    private val TAG = "VpnStatusListener"

    private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    private var isListening = false

    private var currentVpnStatus: Boolean = false
    var actionVpn: ((isVip: Boolean) -> Unit)? = null

    companion object {
        var vpnFlow: MutableStateFlow<Boolean> = MutableStateFlow(false)
    }

    private val networkCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            val caps = connectivityManager.getNetworkCapabilities(network)
            checkVpnStatus(caps)
        }

        override fun onLost(network: Network) {
            super.onLost(network)
            val caps = connectivityManager.getNetworkCapabilities(network)
            checkVpnStatus(caps)
        }

        override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities)
            checkVpnStatus(networkCapabilities)
        }
    }

    fun startListen() {
        if (!isListening) {
            val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_VPN)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
                .build()
            connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
            isListening = true
        }
    }

    fun stopListen() {
        if (isListening) {
            connectivityManager.unregisterNetworkCallback(networkCallback)
            isListening = false
        }
    }

    private fun checkVpnStatus(networkCapabilities: NetworkCapabilities?) {
        val isVpn = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
        // 这里可以根据isVpn的值进行相应处理，比如更新UI等
        if (currentVpnStatus != isVpn) {
            currentVpnStatus = isVpn
            Log.e(TAG, "VpnStatusListener =$isVpn")
            actionVpn?.invoke(isVpn)
            vpnFlow.update { isVpn }
        }
    }
}