package com.pixelized.biblib.repository.connectivity

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow

/**
 * This class is responsible to check for internet availability.
 * https://developer.android.com/training/monitoring-device-state/connectivity-status-type
 */
class ConnectivityRepository constructor(
    @ApplicationContext context: Context,
) : IConnectivityRepository {
    private val _networkAvailabilityFlow = MutableStateFlow(true)

    override val networkAvailabilityFlow: Flow<Boolean> get() = _networkAvailabilityFlow
    override val isNetworkAvailable: Boolean get() = _networkAvailabilityFlow.value

    init {
        context.getSystemService<ConnectivityManager>()?.let { connectivityManager ->

            val networkRequest = NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                .build()

            val networkCallback = object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    super.onAvailable(network)
                    _networkAvailabilityFlow.value = true
                }

                override fun onLost(network: Network) {
                    super.onLost(network)
                    _networkAvailabilityFlow.value = false
                }
            }

            connectivityManager.requestNetwork(networkRequest, networkCallback)
        }
    }
}