package com.bonait.bnframework.common.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.util.Log;

import java.io.DataOutputStream;

/**
 * Created by LY on 2019/1/4.
 */
public class NetworkUtils {
    //判断网络连接是否可用（返回true表示网络可用，false为不可用）
    public static boolean checkNetworkAvailable(Context context) {
        //获取手机所有链接管理对象（包括对Wi-Fi，net等连接的管理）
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        } else {
            //获取NetworkInfo对象
            NetworkInfo[] info = manager.getAllNetworkInfo();
            if (info != null && info.length > 0) {
                for (int i = 0; i < info.length; i++) {
                    System.out.println(i + "状态" + info[i].getState());
                    System.out.println(i + "类型" + info[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    /**
     * 检测当的网络（WLAN、4G/3G/2G）状态，兼容Android 6.0以下
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkConnected(Context context) {
        boolean result = false;
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (cm != null) {
                    NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
                    if (capabilities != null) {
                        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                            result = true;
                        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                            result = true;
                        }
                    }
                }
            } else {
                if (cm != null) {
                    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                    if (activeNetwork != null) {
                        // connected to the internet
                        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                            result = true;
                        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                            result = true;
                        }
                    }
                }
            }

        } catch (Exception e) {
            return false;
        }

        return result;
    }

    /**
     * 判断是否是移动网络连接
     * */
    public static boolean isActiveNetworkMobile(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        }
        return false;
    }

    /**
     * 判断是否是wifi
     * */
    public static boolean isActiveNetworkWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
        }
        return false;
    }

    /**
     * @deprecated 请先使用 {@link NetworkUtils#isNetworkConnected(Context)} 方法
     *
     * 检测当的网络（WLAN、4G/3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    @Deprecated
    public static boolean checkNet(Context context) {

        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {

                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {

                    /*if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }*/
                    NetworkCapabilities networkCapabilities = connectivity.getNetworkCapabilities(connectivity.getActiveNetwork());
                    return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * 绑定有线网络
     * @param context
     */
    public static void connetEnternet(Context context)
    {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET);
        //builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        NetworkRequest networkRequest = builder.build();
        connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                connManager.bindProcessToNetwork(network); // 绑定应用程序到有线网络
            }
        });
    }

    /**
     * 绑定有线网络
     * @param context
     */
    public static void connetWifi(Context context)
    {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        NetworkRequest networkRequest = builder.build();
        connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                connManager.bindProcessToNetwork(network); // 绑定应用程序到有线网络
            }
        });
    }

    /**
     * 同步时间
     */
    public static void SynchronizationTime()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    exec3("settings put global auto_time 0");
                    Thread.sleep(500);
                    exec3("settings put global auto_time 1");
                } catch (InterruptedException e) {

                }
            }
        }).start();
    }
    /**
     * 发送
     * @param cmds
     */
    public static void exec3(String... cmds) {
        StringBuffer command = new StringBuffer();
        if (cmds.length <= 0) {
            return;
        }
        for (String cmd : cmds) {
            command.append(cmd).append("\n");
        }
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su");
            //       process = Runtime.getRuntime().exec("system/bin/su");
            os = new DataOutputStream(process.getOutputStream());
            os.write(command.toString().getBytes());
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("eeee",""+e.toString());
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(process!=null){
                process.destroy();
            }
        }
    }
}
