package com.gh.gamecenter.common.utils;

import static android.os.Build.MANUFACTURER;
import static android.os.Build.MODEL;

import android.app.ActivityManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.core.HaloApp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by khy on 2/08/17.
 */

public class DeviceUtils {

    public static JSONObject getLoginDevice(Context context) throws JSONException { // device数据
        context = context.getApplicationContext();
        JSONObject object = new JSONObject();
        object.put("os", "Android");
        object.put("jnfj", MetaUtil.getBase64EncodedIMEI());
        object.put("mac", "");
        object.put("model", MODEL);
        object.put("manufacturer", MANUFACTURER);
        object.put("dia", MetaUtil.getBase64EncodedAndroidId());
        object.put("android_sdk", Build.VERSION.SDK_INT);
        object.put("android_version", android.os.Build.VERSION.RELEASE);
        object.put("ip", "");
        object.put("network", getNetwork(context));
        return object;
    }

    private static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    public static String getUserAgent() {
        String userAgent = "";
        userAgent = System.getProperty("http.agent");
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                return getCurrentIpAddress();
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    public static String getNetwork(Context context) {
        context = context.getApplicationContext();

        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connManager == null) return null;
        NetworkInfo info = connManager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            int typeMobile = info.getType();
            if (typeMobile == ConnectivityManager.TYPE_WIFI) {
                return "WIFI";
            } else if (typeMobile == ConnectivityManager.TYPE_MOBILE) {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if (telephonyManager != null) {
                    int networkType = telephonyManager.getNetworkType();
                    String status;
                    switch (networkType) {
                        case TelephonyManager.NETWORK_TYPE_GPRS:
                        case TelephonyManager.NETWORK_TYPE_EDGE:
                        case TelephonyManager.NETWORK_TYPE_CDMA:
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                            status = "2G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                            status = "3G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            status = "4G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_NR:
                            status = "5G";
                            break;
                        default:
                            status = "未知";
                            break;
                    }
                    return status;
                }
            }
        }

        return "无网络";
    }

    // ping domain
    public static String ping(String domain) {
        try {
            Process process = Runtime.getRuntime().exec("ping -c 5 " + domain);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append("\n");
            }
            return builder.toString();
        } catch (IOException e) {
            return Log.getStackTraceString(e);
        }
    }

    public static long getTotalRamSizeOfDevice(Context context) {
        ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
        if (actManager != null) {
            actManager.getMemoryInfo(memInfo);
        }
        return memInfo.totalMem / (1024 * 1024);
    }

    // 只能获取WiFi的IpAddress
    public static String getCurrentIpAddress() {
        String ipAddress = "0.0.0.0";
        try {
            WifiManager wifiManager = (WifiManager) HaloApp.getInstance()
                    .getApplicationContext()
                    .getSystemService(Context.WIFI_SERVICE);
            int address = wifiManager.getDhcpInfo().ipAddress;
            ipAddress = ((address & 0xFF)
                    + "." + ((address >> 8) & 0xFF)
                    + "." + ((address >> 16) & 0xFF)
                    + "." + ((address >> 24) & 0xFF));
            return ipAddress;
        } catch (Exception e) {
            return ipAddress;
        }
    }

}
