package com.oo.seex.sys_state.state;

import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.oo.seex.sys_state.Config;
import com.oo.seex.sys_state.Register;
import com.oo.seex.sys_state.state.bean.WifiState;

/**
 * Created by gyp on 17/7/4.
 */

public class WifiStateReceiver extends BaseReceiver {
    private WifiState state;

    public WifiStateReceiver(Context context, Register register) {
        super(context, register);
        state = new WifiState();
        addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        addAction(WifiManager.RSSI_CHANGED_ACTION);
        addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    }

    @Override
    public void onReceive(Context context, Intent intent) {

//        Log.e("onReceive_wifi", "enterWifiState::" + intent.getAction());
        if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
            wifiInfo(state);
        } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {//wifi连接上与否
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//            Log.e("onReceive_wifi", info.getState() + "");
            if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                state.setConnect(false);
                state.setOpen(true);
            } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                state.setConnect(true);
                wifiInfo(state);
            }

        } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {//wifi打开与否
            int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);

            if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
                state.setOpen(false);
            } else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
                state.setOpen(true);
            }
        }
        register.callback(Config.FLAG_WIFI_STATE, state);
    }


    private void wifiInfo(WifiState state) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        state.setSsid(wifiInfo.getSSID());
        state.setStrength(WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5));
        state.setOpen(true);//能走到此方法证明wifi是开启状态

    }

}
