package com.wdkl.app.ncs.callingbed.helper;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;

import com.wdkl.ncs.android.middleware.common.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.wdkl.ncs.android.middleware.common.Constant.EVENT_INTERNETPING;


public class NetHelper {
    private Context mContext;
    private WifiManager wifiManager;
    private ConnectivityManager connManager;
    private static NetHelper sInstance = null;

    private static Timer timerNetStatus = null;
    private static final int SCHEDULE_TIME = 30000;
    public static boolean NetConn = false;

    /**
     * 以太网是否ping成功
     */
    public static final String ETHERNETSTATUS = "ethernetStatus";

    public NetHelper() {
    }

    public static NetHelper getInstance() {
        if (sInstance == null) {
            synchronized (NetHelper.class) {
                if (sInstance == null) {
                    sInstance = new NetHelper();
                }
            }
        }
        return sInstance;
    }

    public void init(Context context) {
        mContext = context;
        wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        connManager = (ConnectivityManager) mContext.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static void startNetCheck() {
        if (timerNetStatus != null) {
            timerNetStatus.purge();
        }
        timerNetStatus = new Timer();
        timerNetStatus.schedule(new TimerTask() {
            @Override
            public void run() {
                NetConn = ping(getLocalElement(3), 2, null);

                EventBus.getDefault().post(new MessageEvent(ETHERNETSTATUS, EVENT_INTERNETPING));//循环检测SIP，以太网ping状态
            }
        }, 10, SCHEDULE_TIME);
    }

    /**
     * ping 网络
     *
     * @param host
     * @param pingCount
     * @param stringBuffer
     * @return
     */
    public static boolean ping(String host, int pingCount, StringBuffer stringBuffer) {
        String line = null;
        Process process = null;
        BufferedReader successReader = null;
        String command = "ping -c " + pingCount + " " + host;
        boolean isSuccess = false;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process == null) {
                append(stringBuffer, "ping fail:process is null.");
                return false;
            }
            successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = successReader.readLine()) != null) {
                append(stringBuffer, line);
            }
            int status = process.waitFor();
            if (status == 0) {
                append(stringBuffer, "exec cmd success:" + command);
                isSuccess = true;
            } else {
                append(stringBuffer, "exec cmd fail.");
                isSuccess = false;
            }
            append(stringBuffer, "exec finished.");
        } catch (IOException e) {
        } catch (InterruptedException e) {
        } finally {
            if (process != null) {
                process.destroy();
            }
            if (successReader != null) {
                try {
                    successReader.close();
                } catch (IOException e) {
                }
            }
        }

        return isSuccess;
    }

    private static void append(StringBuffer stringBuffer, String text) {
        if (stringBuffer != null) {
            stringBuffer.append(text + "\n");
        }
    }

    /**
     * 获取网关  Waderson
     * <p>
     * 1 WIFI情况下获取网关 2 有线网络下的DHCP模式连接 3 有线网络其他连接方式：比如静态ip、pppoe拨号、ipoe拨号等
     */
    public static String getLocalElement(int type) {
        String e = "";
        if (1 == type) {
            //e = getLocalElementByWifi();
        } else if (2 == type) {
            e = getLocalElementByDhcp();
        } else if (3 == type) {
            e = getLocalElementByIp();
        }
        if (!TextUtils.isEmpty(e) && e.length() >= 11 && e.length() <= 15) {
            return e;
        } else {
            return "192.168.101.1";
        }
    }


    /**
     * 有线网络下的DHCP模式连接
     */
    public static String getLocalElementByDhcp() {
        BufferedReader bufferedReader = null;
        String str2 = "";
        String str3 = "getprop dhcp.eth0.gateway";
        Process exec;
        BufferedReader bufferedReader2 = null;
        try {
            exec = Runtime.getRuntime().exec(str3);
            try {
                bufferedReader2 = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            } catch (Throwable th3) {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (exec != null) {
                    exec.exitValue();
                }
            }
            try {
                str3 = bufferedReader2.readLine();
                if (str3 != null) {
                    TextUtils.isEmpty(str3);
                }
                try {
                    bufferedReader2.close();
                } catch (IOException iOException222) {
                    iOException222.printStackTrace();
                }
                if (exec != null) {
                    try {
                        exec.exitValue();
                    } catch (Exception e5) {
                    }
                }
            } catch (IOException e6) {
                str3 = str2;
                if (bufferedReader2 != null) {
                    bufferedReader2.close();
                }
                if (exec != null) {
                    exec.exitValue();
                }
                return str3;
            }
        } catch (IOException e62) {
            bufferedReader2 = null;
            exec = null;
            str3 = str2;
            if (bufferedReader2 != null) {
                try {
                    bufferedReader2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (exec != null) {
                exec.exitValue();
            }
            return str3;
        } catch (Throwable th4) {
            exec = null;
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (exec != null) {
                exec.exitValue();
            }
        }
        return str3;
    }

    /**
     * 有线网络其他连接方式：比如静态ip、pppoe拨号、ipoe拨号等
     */
    public static String getLocalElementByIp() {
        BufferedReader bufferedReader = null;
        String result = "";
        String str2 = "";
        String str3 = "ip route list table 0";
        Process exec;
        BufferedReader bufferedReader2 = null;
        try {
            exec = Runtime.getRuntime().exec(str3);
            try {
                bufferedReader2 = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            } catch (Throwable th3) {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (exec != null) {
                    exec.exitValue();
                }
            }
            try {
                str2 = bufferedReader2.readLine();
                if (str2 != null) {
                    str2 = str2.trim();
                    String[] strings = str2.split("\\s+");
                    if (strings.length > 3) {
                        result = strings[2];
                    }
                }
                try {
                    bufferedReader2.close();
                } catch (IOException iOException222) {
                    iOException222.printStackTrace();
                }
                if (exec != null) {
                    try {
                        exec.exitValue();
                    } catch (Exception e5) {
                    }
                }
            } catch (IOException e6) {
                if (bufferedReader2 != null) {
                    bufferedReader2.close();
                }
                if (exec != null) {
                    exec.exitValue();
                }
                return result;
            }
        } catch (IOException e62) {
            bufferedReader2 = null;
            exec = null;
            if (bufferedReader2 != null) {
                try {
                    bufferedReader2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (exec != null) {
                exec.exitValue();
            }
            return result;
        } catch (Throwable th4) {
            exec = null;
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (exec != null) {
                exec.exitValue();
            }
        }
        return result;
    }

    /**
     * 得到MAC
     *
     * @return String
     */
    public String getMacAddress() {
        String mac = "";
        try {
            mac = getLocalMacAddressFromIp();
            if (TextUtils.isEmpty(mac)) {
                mac = getNetworkMac();
            }
            if (TextUtils.isEmpty(mac)) {
                mac = tryGetWifiMac();
            }
        } catch (Exception e) {
        }
        return mac;
    }

    public String tryGetWifiMac() {
        String mac;
        WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wm.getConnectionInfo();
        if (wi == null || wi.getMacAddress() == null) {
            mac = null;
        }
        if ("02:00:00:00:00:00".equals(wi.getMacAddress().trim())) {
            mac = null;
        } else {
            mac = wi.getMacAddress().trim();
        }
        return mac;
    }

    /**
     * 通过网络接口获取
     *
     * @return
     */
    public static String getNetworkMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                // if (!nif.getName().equalsIgnoreCase("wlan0") && !nif.getName().equalsIgnoreCase("eth0") && !nif.getName().equalsIgnoreCase("eth1"))
                if (!nif.getName().equalsIgnoreCase("eth0") && !nif.getName().equalsIgnoreCase("eth1") && !nif.getName().equalsIgnoreCase("eth2"))
                    continue;
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 根据IP地址获取MAC地址
     *
     * @return
     */
    @SuppressLint("NewApi")
    public String getLocalMacAddressFromIp() {
        String strMacAddr = null;
        try {
            // 获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip)
                    .getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();

        } catch (Exception e) {

        }

        return strMacAddr;
    }

    public InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            // 列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface
                    .getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = en_netInterface
                        .nextElement();// 得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }


        return ip;
    }

    public String getLocalIP() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean isBTConnected() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter != null) {
            return btAdapter.getState() == BluetoothAdapter.STATE_ON;
        }

        return false;
    }

    public int getNetworkType() {
        if (connManager != null && connManager.getActiveNetworkInfo() != null) {
            return connManager.getActiveNetworkInfo().getType();
        }

        return -1;
    }

    public boolean networkAvailable() {
        if (connManager != null && connManager.getActiveNetworkInfo() != null) {
            return connManager.getActiveNetworkInfo().isConnected();
        }

        return false;
    }
}
