package com.ifavine.pay.utils;

import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static android.content.Context.WIFI_SERVICE;


public class NetUtil {

    /**
     * @Name:pingIP
     * @Description:ping一个网站或者ip
     * @param:@param address 需要ping的地址
     * @param:@return
     * @return:boolean
     * @throw
     * @date:2014-11-14
     */
    public static boolean pingIP(String address) {
        Process p;
        int status = -1;
        try {
            // ping -c 3 -w 100 中 ，-c 是指ping的次数 3是指ping 3次 ，-w 100
            // 以秒为单位指定超时间隔，是指超时时间为100秒
            p = Runtime.getRuntime().exec("ping -c 1 -w 3 " + address);
            status = p.waitFor(); // status 只能获取是否成功，无法获取更多的信息
            if (status == 0) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * @Name:pingIP
     * @Description:ping一个网站或者ip
     * @param:@param address 需要ping的地址
     * @param:@return
     * @return:boolean
     * @throw
     * @date:2014-11-14
     */
    public static boolean pingMachineIP(String address) {
        Process p;
        try {
            p = Runtime.getRuntime().exec("ping -c 1 " + address);
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            TLog.log("test", "pingMachineIP =="
                    + buffer.toString().trim().length());
            TLog.log("test", "pingMachineIP ==" + buffer.toString());
            if (buffer.toString().trim().length() > 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getSSID(Context context) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        TLog.log("ssid", "get connected SSID=="
                + wifiInfo.getSSID().replaceAll("\"", ""));
        return wifiInfo.getSSID().replaceAll("\"", "");
    }

    /**
     * @Name:IsWiFiConnected
     * @param:@param context
     * @param:@return
     * @return:boolean
     * @date:2014-9-28
     */
    public static boolean IsWiFiConnected(Context context) {
        if (context == null) {
            return false;
        }
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null) {
            int type = netInfo.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                return true;
            }
        }
        return false;
    }

    /**
     * @Name:netConnetced
     * @Description:
     * @param:@param context
     * @param:@return
     * @return:boolean
     * @throw
     * @date:2014-9-28
     */
    public static boolean isNetConnetced(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isAvailable()) {
            return true;
        }
        return false;
    }

    /**
     * 打开wifi设置
     */
    public static void setNetworkMethod(final Context context) {
        Builder builder = new Builder(context);
        builder.setTitle("设置网络")
                .setMessage("设置网络？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Intent intent = null;
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(
                                    android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 获取网络ip地址
     */
    public static String getNetWorkIp(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // 判断WIFI网络是否可用
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // 判断WIFI网络是否可用
                // 获得WIFI连接状况ipStringPart、macString，判断WIFI如果ip是10.10.100.＊＊＊，那么连接10.10.100.254
                WifiManager wifiManager = (WifiManager) context
                        .getSystemService(WIFI_SERVICE); // 获取wifi服务
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                String ipStringPart = (ipAddress & 0xFF) + "."
                        + ((ipAddress >> 8) & 0xFF) + "."
                        + ((ipAddress >> 16) & 0xFF);
                String ip = ipStringPart + ".255";
                Log.i("udp", ip);
                return ip;
            }
        }
        return "255.255.255.255";

    }

    public static boolean IsSameWiFiConnected(Context context, String kettleWifi) {
        if (context == null) {
            return false;
        }
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null) {
//			String localWifi="\""+wifiInfo.getSSID()+"\"";
            String localWifi = wifiInfo.getSSID().replace("\"", "");
            if (kettleWifi != null && TextUtils.equals(kettleWifi, localWifi)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    public static String getMobileWiFiNAme(Context context) {
        String localWifi = "";
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            localWifi = wifiInfo.getSSID().replace("\"", "");
        }
        return localWifi;
    }

    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    /**
     * 获取当前网络类型
     *
     * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
     */
    public static int checkNet(Context context) {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!TextUtils.isEmpty(extraInfo)) {
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    public static boolean isWiFiConnected(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return false;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            return false;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }
}
