package com.img.rabbit.viewmodel

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.img.rabbit.config.Constants
import com.img.rabbit.provider.api.ApiManager
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.utils.MMKVUtils.mmkv
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@SuppressLint("ObsoleteSdkInt")
class GeneralViewModel(application: Application) : AndroidViewModel(application) {
    lateinit var api: IWXAPI
    private val _networkStatus = MutableLiveData<Boolean>()
    val networkStatus: LiveData<Boolean> = _networkStatus
    fun setNetworkStatus(status: Boolean) {
        _networkStatus.value = status
    }

    private val _serverTime = mutableStateOf<Long?>(null)
    val serverTime: State<Long?> = _serverTime

    private val _isNavigationBarVisible = MutableLiveData<Boolean>()
    val isNavigationBarVisible: LiveData<Boolean> = _isNavigationBarVisible

    private val connectivityManager =
        application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    private val networkCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            _networkStatus.postValue(true)
        }

        override fun onLost(network: Network) {
            _networkStatus.postValue(false)
        }
    }

    private val _agreementStatus = MutableLiveData<Boolean>()
    val agreementStatus: LiveData<Boolean> = _agreementStatus
    private fun getIsAgreement(): Boolean{
        return mmkv.getBoolean("isAgreement", false)
    }

    init {
        // 注册网络监听
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(networkCallback)
        } else {
            val request = NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build()
            connectivityManager.registerNetworkCallback(request, networkCallback)
        }

        // 初始化状态
        _networkStatus.value = isNetworkAvailable()
        // 初始化隐私政策状态
        _agreementStatus.value = getIsAgreement()

        // 初始化微信API
        initWXApi(application)
    }

    private fun isNetworkAvailable(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork
            val capabilities = connectivityManager.getNetworkCapabilities(network)
            capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo
            networkInfo != null && networkInfo.isConnected
        }
    }

    fun setNavigationBarVisible(visible: Boolean){
        _isNavigationBarVisible.value = visible
    }

    fun setIsAgreement(agreement: Boolean){
        mmkv.putBoolean("isAgreement", agreement)
        _agreementStatus.value = agreement
    }

    private fun initWXApi(context: Context) {
        api = WXAPIFactory.createWXAPI(context, Constants.WechatAppId)
    }

    override fun onCleared() {
        super.onCleared()
        connectivityManager.unregisterNetworkCallback(networkCallback)
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun getServerTime() {
        GlobalScope.launch {
            val response =  ApiManager.serviceVo.getServerTime()
            if (response.status) {
                _serverTime.value = response.data
                PreferenceUtil.setTimeDiff(response.data - System.currentTimeMillis() / 1000)
            }
        }
    }
}