package com.tcl.ah.tvcontrol.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import com.tcl.ah.tvcontrol.MyApplication;
import com.tcl.snack.net.Nets;

public class NetworkBroadcastReceiver extends BroadcastReceiver {
    private Context mContext;
    private IntentFilter mIntentFilter;
    private boolean isRegister = false;
    private Callback mCallback;
    public final String connectivityAction = ConnectivityManager.CONNECTIVITY_ACTION;

    public NetworkBroadcastReceiver(Context context) {
        mContext = context;
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        //mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        //mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        isRegister = false;
    }

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

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            if (Nets.isNetWorkConnected(MyApplication.getAppContext())) {
                if (mCallback != null) {
                    mCallback.onReceive(context, intent);
                }
            }
        }
    }

    public void register() {
        if (!isRegister) {
            mContext.registerReceiver(this, mIntentFilter);
        }
    }

    public void unRegister() {
        if (isRegister) {
            mContext.unregisterReceiver(this);
        }
    }

    public NetworkBroadcastReceiver setCallback(Callback callback) {
        mCallback = callback;
        return this;
    }

    public interface Callback {
        void onReceive(Context context, Intent intent);
    }
}
