package com.bonait.bnframework.common.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * wifi
 */
public class WifiInterceptor implements Interceptor {
    private Context context;

    public WifiInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        NetworkRequest networkRequest = builder.build();

        ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                connManager.bindProcessToNetwork(network); // 绑定应用程序到 Wi-Fi 网络
            }
        };

        connManager.requestNetwork(networkRequest, networkCallback);

        try {
            Request request = chain.request();
            Response response = chain.proceed(request);
            return response;
        } finally {
            connManager.unregisterNetworkCallback(networkCallback);
        }
    }
}
