package com.epson.mobilephone.common.wifidirect;

import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;

import java.lang.ref.WeakReference;

/**
 * wifi扫描工具类
 */
public class WiFiScanner {
    private static final int INTERVAL_SCAN = 30;
    private static Handler wifiScannerHandler;
    private static Object wifiScannerToken;
    private String TAG = "WiFiScanner";
    private WeakReference<WifiManager> refWiFiManager = null;

    public boolean startScan(WifiManager wifiManager) {
        if (Build.VERSION.SDK_INT >= 28) {
            if (wifiScannerHandler == null) {
                wifiScannerHandler = new Handler();
                wifiScannerToken = new Object();
            }
            wifiScannerHandler.removeCallbacksAndMessages(wifiScannerToken);
            refWiFiManager = new WeakReference<>(wifiManager);
            wifiScannerHandler.postDelayed(new Runnable() {
                public void run() {
                    WifiManager wifiManager = (WifiManager) WiFiScanner.this.refWiFiManager.get();
                    if (WiFiScanner.this.refWiFiManager != null) {
                        EPLog.d(WiFiScanner.this.TAG, "Started Delayed startScan()");
                        if (!wifiManager.startScan()) {
                            EPLog.e(WiFiScanner.this.TAG, "Failed Delayed startScan()");
                        }
                    }
                }
            }, wifiScannerToken, 30000);
            return true;
        } else if (wifiManager.startScan()) {
            return true;
        } else {
            EPLog.e(this.TAG, "Failed startScan()");
            return false;
        }
    }
}
