package com.zkjc.common.broadcast;

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

import com.jess.arms.integration.EventBusManager;
import com.zkjc.common.event.NetEvent;
import com.zkjc.common.utils.ApkUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

public class NetBroadcastReceiver extends BroadcastReceiver {

//    public NetEvent event= BaseActivity.event;

    @Override
    public void onReceive(Context context, Intent intent) {
        // 如果相等的话就说明网络状态发生了变化
        if (ApkUtils.isDemo(context))
            return;
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)
                || intent.getAction().equals(Intent.ACTION_SCREEN_ON)
                || intent.getAction().equals(Intent.ACTION_USER_PRESENT)
                || intent.getAction().equals(Intent.ACTION_USER_UNLOCKED)) {
//            ToastUtils.show("网络状态有变化，正在ping主机192.168.20.228");
            Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
                emitter.onNext(isPingOk("192.168.20.228"));
                emitter.onComplete();
            })
                    .doOnSubscribe(disposable -> {
                        Timber.v("requestLogin===doOnSubscribe:" + Thread.currentThread().getName());
//                addDispose(disposable);//在订阅时必须调用这个方法,不然Activity退出时可能内存泄漏
                    }).subscribeOn(Schedulers.io())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
//            .throttleLast(3000, TimeUnit.SECONDS)
                    .subscribe(o -> {
                        if (!o) EventBusManager.getInstance().post(new NetEvent());
                    });
            /*int netWorkState = NetUtil.getNetWorkState(context);
            // 接口回调传过去状态的类型
            event.onNetChange(netWorkState);*/
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            EventBusManager.getInstance().post(new NetEvent(false));
        }
    }

    public boolean isPingOk(String ip) {
        try {
            Process p = Runtime.getRuntime().exec("/system/bin/ping -c 10 -w 4 " + ip);
            if (p == null) {
                return false;
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                if (line.contains("bytes from")) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 推断Ping 网址是否返回成功
     *
     * @param m_strForNetAddress
     * @return
     */
    public String isPingSuccess(int pingNum, String m_strForNetAddress) {
        StringBuffer tv_PingInfo = new StringBuffer();
        try {


            Process p = Runtime.getRuntime().exec("/system/bin/ping -c " + pingNum + " " + m_strForNetAddress); // 10.83.50.111
            // m_strForNetAddress
            int status = p.waitFor();
            String result = "";
            if (status == 0) {
                result = "success";
            } else {
                result = "failed";
            }
            String lost = new String();
            String delay = new String();
            BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));


            String str = new String();
            // 读出全部信息并显示
            while ((str = buf.readLine()) != null) {
                str = str + "\r\n";
                tv_PingInfo.append(str);
            }


            return tv_PingInfo.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
}