package com.epson.mobilephone.common.wifidirect;

import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

@RequiresApi(api = 21)
public class WiFiNetworkManager {
    private static final String TAG = "WiFiNetworkManager";
    private static WiFiNetworkManager instance;
    ConnectivityManager connectivityManager;
    Context context;

    private WiFiNetworkManager(@NonNull Context context2) {
        context = context2;
        connectivityManager = (ConnectivityManager) context2.getSystemService(Service.CONNECTIVITY_SERVICE);
    }

    public static WiFiNetworkManager getInsetance(@NonNull Context context2) {
        if (instance == null) {
            instance = new WiFiNetworkManager(context2);
        }
        return instance;
    }

    protected Network getWifiNetwork() {
        for (Network network : connectivityManager.getAllNetworks()) {
            if (connectivityManager.getNetworkCapabilities(network).hasTransport(1)) {
                return network;
            }
        }
    }

    @RequiresApi(api = 23)
    public boolean isWiFiValidated() {
        Network wifiNetwork = getWifiNetwork();
        if (wifiNetwork != null) {
            NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(wifiNetwork);
            if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                EPLog.d(TAG, "capabilities :" + networkCapabilities.toString());
                EPLog.d(TAG, "isWiFiValidated = OK : " + WiFiUtils.getInstance(context).getCurSSID());
                return true;
            }
        }
        return false;
    }
}
