package es.verdnatura.presentation.common

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import es.verdnatura.MobileApplication
import es.verdnatura.R
import es.verdnatura.presentation.view.feature.main.activity.MainActivity

class NetworkUtilsApp(context: Context, applicationContext: MobileApplication) {

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

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

            override fun onLost(network: Network) {
                applicationContext.hasNetwork = false
                (context as MainActivity).messageWithSound(
                    context.getString(R.string.sin_internet),
                    true,
                    false
                )

            }
        }

    fun registerNetworkCallback() {
        val networkRequest = NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .build()
        connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
    }

    fun unregisterNetworkCallback() {
        connectivityManager.unregisterNetworkCallback(networkCallback)
    }
}
