package basic.app.netstatus;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by fanwang on 12/19/16.
 * this class is used to watch net status,and notify the listeners
 */
public class NetStatusWatcher {
    private static NetStatusWatcher sInstance = null;

    private NetStatusWatcher(){}

    public static NetStatusWatcher getsInstance(){
        if(sInstance == null){
            synchronized (NetStatusWatcher.class){
                if(sInstance == null){
                    sInstance  = new NetStatusWatcher();
                }
            }
        }

        return sInstance;
    }

    public interface OnNetStateListener {
        public void onStateChanged(int state);
    }

    public static final int ETHERNET_CONNECTED = 0;
    public final static int ETHERNET_DISCONNECTED = 1;
    public static final int WIFI_CONNECTED = 2;
    public final static int WIFI_DISCONNECTED = 3;
    private static int connType = WIFI_DISCONNECTED;
    public static int MAIN_PAGERVIEW_POSITION = 0;
    private static List<OnNetStateListener> onNetStateListenerList = new ArrayList<OnNetStateListener>();

    public static void addOnNetStateListener(OnNetStateListener onsl) {
        if(onsl != null && !onNetStateListenerList.contains(onsl)) {
            onNetStateListenerList.add(onsl);
        }
    }

    public static void removeOnNetStateListener(OnNetStateListener onsl) {
        if(onsl != null) {
            onNetStateListenerList.remove(onsl);
        }
    }

    public static void updateNetConn(Context context) {

        connType = getNetConnStatus(context);

        for(OnNetStateListener nsl: onNetStateListenerList) {
            if(nsl != null) {
                nsl.onStateChanged(connType);
            }
        }
    }

    @SuppressLint("InlinedApi")
    public static int getNetConnStatus(Context context) {
        ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        int status = WIFI_DISCONNECTED;

        if(wifiNetInfo != null && wifiNetInfo.isAvailable() && wifiNetInfo.isConnected()) {
            status = WIFI_CONNECTED;
        } else {
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
            if(networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
                status = ETHERNET_CONNECTED;
            }
        }

        return status;
    }

}
