package com.ruiwenliu.wrapper.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;
import android.widget.Toast;

import com.base.utils.tools.android.NetworkUtil;
import com.rv.component.utils.LogUtil;

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

public class NetWorkReceiver extends BroadcastReceiver {

    private List<NetChangListener> listeners = new ArrayList<>();

    private static NetWorkReceiver instance = null;

    private NetWorkReceiver() {
    }

    public static NetWorkReceiver getInstance() {
        if (instance == null) {
            instance = new NetWorkReceiver();
        }
        return instance;
    }

    public void register(NetChangListener listener) {
        listeners.add(listener);
    }

    public void unRegister(NetChangListener listener) {
        if (listeners.contains(listener)) {
            listeners.remove(listener);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            if (NetworkUtil.isNetworkAvailable(context)) {
                // 网络可用
                LogUtil.d("xxxxxx", "网络正常");
                if (!listeners.isEmpty()) {
                    for (NetChangListener listener : listeners) {
                        listener.netAvailable();
                    }
                }
            } else {
                Toast.makeText(context, "网络已断开！", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public interface NetChangListener {
        // 网络可用
        void netAvailable();

        // 网络不可用或者无网络
        void netUnAvailable();
    }
}
