/**
 * Cobub Razor
 * <p>
 * An open source analytics android sdk for mobile applications
 *
 * @package Cobub Razor
 * @author WBTECH Dev Team
 * @copyright Copyright (c) 2011 - 2012, NanJing Western Bridge Co.,Ltd.
 * @license http://www.cobub.com/products/cobub-razor/license
 * @link http://www.cobub.com/products/cobub-razor/
 * @filesource
 * @since Version 0.1
 */
package com.oo.seex.oo_statistics_lib.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.oo.seex.oo_statistics_lib.bean.StatistivsBean;
import com.oo.seex.oo_statistics_lib.constant.OOConstant;
import com.oo.seex.oo_statistics_lib.dao.SaveInfo;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 基本信息工具类
 */
public class CommonUtil {

    /**
     * 保存信息到文件中；
     *
     * @param handler
     * @param type    统计类型
     * @param info    统计信息
     * @param context
     */
    public static void saveInfoToFile(Handler handler, String type,
                                      StatistivsBean info, Context context) {
        info.setType(type);
        if (handler != null) {
            handler.post(new SaveInfo(context, info));
        } else {
            CommonUtil.printLog(CommonUtil.getActivityName(context),
                    "handler--null");
        }
    }

    /**
     * checkPermissions
     * 检查我们的应用是否有某个权限
     *
     * @param context
     * @param permission 权限字符串（清单文件中相同的字符串）
     * @return true or false
     */
    public static boolean checkPermissions(Context context, String permission) {
        PackageManager localPackageManager = context.getPackageManager();
        return localPackageManager.checkPermission(permission,
                context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * Determine the current networking is WIFI
     * 检查当前是否是处于wifi环境下
     *
     * @param context
     * @return
     */
    public static boolean currentNoteworkTypeIsWIFI(Context context) {
        ConnectivityManager connectionManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        return connectionManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * return UserIdentifier
     * 返回用户标示   也就是userID
     */
    public static String getUserIdentifier(Context context) {
        String userId = FileUtil.getUserIdToFile();
        if(TextUtils.isEmpty(userId)){
            userId = "0";
        }
        //如果没有保存到userId，则上传的userId 默认值是：0；
        return userId;

    }
    /**
     * return os_version
     * 返回os version
     */
    public static String getOSVersion(Context context) {
        String version = FileUtil.getOSToFile();
        if(TextUtils.isEmpty(version)){
            version = "0";
        }
        return version;

    }

    /**
     * Judge wifi is available
     * 检测wifi是否有效   （是否连上互联网）
     *
     * @param inContext
     * @return
     */
    public static boolean isWiFiActive(Context inContext) {
        if (checkPermissions(inContext, "android.permission.ACCESS_WIFI_STATE")) {
            Context context = inContext.getApplicationContext();
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null) {
                    for (int i = 0; i < info.length; i++) {
                        if (info[i].getTypeName().equals("WIFI")
                                && info[i].isConnected()) {
                            return true;
                        }
                    }
                }
            }
            return false;
        } else {
            Log.e("lost permission",
                    "lost--->android.permission.ACCESS_WIFI_STATE");

            return false;
        }
    }

    /**
     * Testing equipment networking and networking WIFI
     * 是否又网络  同时判断时否又互联网以及Wi-Fi 返回状态
     *
     * @param context
     * @return true or false
     */
    public static boolean isNetworkAvailable(Context context) {
        if (checkPermissions(context, "android.permission.INTERNET")) {
            ConnectivityManager cManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                return true;
            } else {
                Log.e("error", "Network error");
                return false;
            }

        } else {
            Log.e("lost  permission",
                    "lost----> android.permission.INTERNET");

            return false;
        }

    }

    /**
     * Get the current time format yyyy-MM-dd HH:mm:ss
     * 获取实时时间  yyyy-MM-dd HH:mm:ss 格式返回
     *
     * @return 时间
     */
    public static long getTime() {
//        Date date = new Date();
//        SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(
//                "yyyy-MM-dd HH:mm:ss");
//        return localSimpleDateFormat.format(date);
        return System.currentTimeMillis() / 1000;
    }

    /**
     * get APPKEY
     * 获取 APPKEY  这里必须在我们应用的清单文件中有配置这个信息； 用来与服务端区分应用类型；
     *
     * @param paramContext
     * @return appkey
     */
    public static String getAppKey(Context paramContext) {
        if (paramContext == null) {
            return "";
        }
        String shincAppkey;
        try {
            PackageManager localPackageManager = paramContext
                    .getPackageManager();
            ApplicationInfo localApplicationInfo = localPackageManager
                    .getApplicationInfo(paramContext.getPackageName(), PackageManager.GET_META_DATA );
            if (localApplicationInfo != null) {
                String str = localApplicationInfo.metaData
                        .getString("OO_APPKEY");
                if (str != null) {
                    shincAppkey = str;
                    return shincAppkey.toString();
                }
                Log.e("OOAgent", "Could not read OO_APPKEY meta-data from AndroidManifest.xml.");
            }
        } catch (Exception localException) {
            Log.e("OOAgent", "Could not read OO_APPKEY meta-data from AndroidManifest.xml.");
        }
        return "";
    }


    /**
     * getAppPlatform
     * 获取 getAppPlatform  这里必须在我们应用的清单文件中有配置这个信息； 用来与服务端区分应用类型；
     *
     * @param paramContext
     * @return AppPlatform
     */
    public static String getAppPlatform(Context paramContext) {
        if (paramContext == null) {
            return "";
        }
        String shincAppkey;
        try {
            PackageManager localPackageManager = paramContext
                    .getPackageManager();
            ApplicationInfo localApplicationInfo = localPackageManager
                    .getApplicationInfo(paramContext.getPackageName(), PackageManager.GET_META_DATA );
            if (localApplicationInfo != null) {
                String str = localApplicationInfo.metaData
                        .getString("OO_APP_PLATFORM");
                if (str != null) {
                    shincAppkey = str;
                    return shincAppkey.toString();
                }
                Log.e("OOAgent", "Could not read OO_APP_PLATFORM meta-data from AndroidManifest.xml.");
            }
        } catch (Exception localException) {
            Log.e("OOAgent", "Could not read OO_APP_PLATFORM meta-data from AndroidManifest.xml.");
        }
        return "";
    }

    /**
     * get channel
     * 获取 channel  这里必须在我们应用的清单文件中有配置这个信息； 用来与服务端区分应用类型；
     *
     * @param paramContext
     * @return channel
     */
    public static String getChannel(Context paramContext) {
        if (paramContext == null) {
            return "";
        }
        String chennel;
        try {
            PackageManager localPackageManager = paramContext
                    .getPackageManager();
            ApplicationInfo localApplicationInfo = localPackageManager
                    .getApplicationInfo(paramContext.getPackageName(), PackageManager.GET_META_DATA );
            if (localApplicationInfo != null) {
                String str = localApplicationInfo.metaData
                        .getString("CHANNEL");
                if (str != null) {
                    chennel = str;
                    return chennel.toString();
                }
                Log.e("OOAgent",
                        "Could not read CHANNEL meta-data from AndroidManifest.xml.");
            }
        } catch (Exception localException) {
            Log.e("OOAgent",
                    "Could not read CHANNEL meta-data from AndroidManifest.xml.");
//                localException.printStackTrace();
        }
        return "";
    }

    /**
     * get MASTER_KEY
     * 获取 MASTER_KEY  这里必须在我们应用的清单文件中有配置这个信息； 用来与服务端区分应用类型；
     *
     * @param paramContext
     * @return MASTER_KEY
     */
    public static String getMasterKey(Context paramContext) {
        if (paramContext == null) {
            return "";
        }
        String chennel;
        try {
            PackageManager localPackageManager = paramContext
                    .getPackageManager();
            ApplicationInfo localApplicationInfo = localPackageManager
                    .getApplicationInfo(paramContext.getPackageName(), PackageManager.GET_META_DATA );
            if (localApplicationInfo != null) {
                String str = localApplicationInfo.metaData
                        .getString("MASTER_KEY");
                if (str != null) {
                    chennel = str;
                    return chennel.toString();
                }
//                if (ShiNcConstant.DebugMode)
                Log.e("OOAgent", "Could not read MASTER_KEY meta-data from AndroidManifest.xml.");
            }
        } catch (Exception localException) {
            Log.e("OOAgent",
                    "Could not read MASTER_KEY meta-data from AndroidManifest.xml.");
//                localException.printStackTrace();
        }
        return "";
    }

    /**
     * get currnet activity's name
     * 获取当前组件的名称；用来统计页面访问
     *
     * @param context
     * @return 当前栈顶activity的名字
     */
    public static String getActivityName(Context context) {
        if (context == null) {
            return "";
        }
        String contextString = context.toString();
        return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
    }

    /**
     * get PackageName
     * 获取应用包名
     *
     * @param context
     * @return
     */
    public static String getPackageName(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        if (checkPermissions(context, "android.permission.GET_TASKS")) {
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            return cn.getPackageName();
        } else {
            Log.e("lost permission", "android.permission.GET_TASKS");

            return "";
        }

    }

//    /**
//     * get OS number
//     * 固件版本号
//     *
//     * @param context
//     * @return
//     */
//    public static String getOsVersion(Context context) {
//        String osVersion = "";
//        if (checkPhoneState(context)) {
//            // 获取手机固件版本号
//            osVersion = Build.VERSION.RELEASE;
//            printLog("android_osVersion", "OsVerson" + osVersion);
//            return osVersion;
//        } else {
//            printLog("android_osVersion", "OsVerson get failed");
//            return osVersion;
//        }
//    }

    /**
     * get deviceid
     * 安卓手机唯一标示码
     *
     * @param context add <uses-permission android:name="READ_PHONE_STATE" />
     * @return
     */
    public static String getDeviceID(Context context) {
        if (context == null) {
            return "";
        }
//        String deviceId = UTDevice.getUtdid(context);// 这里就是阿里的

//        return TextUtils.isEmpty(SharePreferenceUtils.getInstance(context).getDeviceId()) ? deviceId : SharePreferenceUtils.getInstance(context).getDeviceId();
        return SharePreferenceUtils.getInstance(context).getDeviceId();
    }

    /**
     * check phone _state is readied ;
     * 检查手机是否允许我获得手机状态；
     *
     * @param context
     * @return 允许返回true
     */
    public static boolean checkPhoneState(Context context) {
        PackageManager packageManager = context.getPackageManager();
        if (packageManager
                .checkPermission("android.permission.READ_PHONE_STATE",
                        context.getPackageName()) != 0) {
            return false;
        }
        return true;
    }


    public static boolean checkLocationState(Context context) {
        PackageManager packageManager = context.getPackageManager();
        if (packageManager.checkPermission("android.permission.ACCESS_COARSE_LOCATION", context.getPackageName()) != 0) {
            return false;
        }
        return true;
    }

    public static boolean checkWifiState(Context context) {
        PackageManager packageManager = context.getPackageManager();
        if (packageManager.checkPermission("android.permission.ACCESS_WIFI_STATE", context.getPackageName()) != 0) {
            return false;
        }
        return true;
    }

    /**
     * Get the current send model
     * 是否实时发送消息
     *
     * @param context
     * @return
     */
    public static int getReportPolicyMode(Context context) {
        String str = context.getPackageName();
        SharedPreferences localSharedPreferences = context
                .getSharedPreferences("shincsdk_share" + str, 0);
        int type = localSharedPreferences.getInt("shinc_report_policy", 2);
        return type;
    }

    /**
     * To determine whether it contains a gyroscope
     * 是否有重力感应（是否有传感器）
     *
     * @return
     */
    public static boolean isHaveGravity(Context context) {
        SensorManager manager = (SensorManager) context
                .getSystemService(Context.SENSOR_SERVICE);
        if (manager == null) {
            return false;
        }
        return true;
    }

    /**
     * Get the current networking
     * 返回网络类型
     * 2g 3g 啥都有
     *
     * @param context
     * @return WIFI or MOBILE
     */
    public static String getNetworkType(Context context) {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        int type = manager.getNetworkType();
        String typeString = "UNKNOWN";
        if (type == TelephonyManager.NETWORK_TYPE_CDMA) {
            typeString = "CDMA";
        }
        if (type == TelephonyManager.NETWORK_TYPE_EDGE) {
            typeString = "EDGE";
        }
        if (type == TelephonyManager.NETWORK_TYPE_EVDO_0) {
            typeString = "EVDO_0";
        }
        if (type == TelephonyManager.NETWORK_TYPE_EVDO_A) {
            typeString = "EVDO_A";
        }
        if (type == TelephonyManager.NETWORK_TYPE_GPRS) {
            typeString = "GPRS";
        }
        if (type == TelephonyManager.NETWORK_TYPE_HSDPA) {
            typeString = "HSDPA";
        }
        if (type == TelephonyManager.NETWORK_TYPE_HSPA) {
            typeString = "HSPA";
        }
        if (type == TelephonyManager.NETWORK_TYPE_HSUPA) {
            typeString = "HSUPA";
        }
        if (type == TelephonyManager.NETWORK_TYPE_UMTS) {
            typeString = "UMTS";
        }
        if (type == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
            typeString = "UNKNOWN";
        }
        if (type == TelephonyManager.NETWORK_TYPE_1xRTT) {
            typeString = "1xRTT";
        }
        if (type == 11) {
            typeString = "iDen";
        }
        if (type == 12) {
            typeString = "EVDO_B";
        }
        if (type == 13) {
            typeString = "LTE";
        }
        if (type == 14) {
            typeString = "eHRPD";
        }
        if (type == 15) {
            typeString = "HSPA+";
        }

        return typeString;
    }

    /**
     * Get the current application version number
     * 获取应用版本号
     *
     * @param context
     * @return
     */
    public static String getVersion(Context context) {
        String versionName = "";
        try {
            if (context == null) {
                return "";
            }
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            if (OOConstant.DebugMode) {

            }

        }
        return versionName;
    }

    /**
     * Set the output log
     * 打印Log日志
     *
     * @param tag
     * @param log
     */

    public static void printLog(String tag, String log) {
        if (OOConstant.DebugMode == true) {
            Log.e(tag, log + " ");
        }
    }

    public static void printLog(Throwable log) {
        if (OOConstant.DebugMode == true) {
            log.printStackTrace();
        }
    }

    /**
     * 获取网络类型
     *
     * @param context
     * @return
     */
    public static String getNetworkTypeWIFI2G3G(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = cm.getActiveNetworkInfo();
        String type = info.getTypeName().toLowerCase();
        if (type.equals("wifi")) {

        } else {
            type = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                    .getExtraInfo();
            System.out.println(type);
        }
        return type;

    }


    /**
     * Get device name, manufacturer + model
     * 设备生产厂家   以及机型
     *
     * @return device name
     */
    public static String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;

        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    /**
     * Capitalize the first letter
     * 首字母大些的方法。。。。。。。。这也抽取了一个方法
     *
     * @param s model,manufacturer
     * @return Capitalize the first letter
     */
    private static String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    /**
     * 是否间隔时间到了
     *
     * @param context
     * @return
     */
    public static boolean isInteval(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("shincsdk_share",
                Context.MODE_PRIVATE);
        Long startInteval = preferences.getLong("shinc_inteval_start", 0);
        Long curTime = Long.valueOf(System.currentTimeMillis());
        if (curTime - startInteval > OOConstant.IntervalMillis) {
            preferences.edit().putLong("shinc_inteval_start", curTime).apply();
            return true;
        } else {
            return false;
        }
    }

    public static String getBrowserApp(Context context) {
        String default_browser = "android.intent.category.DEFAULT";
        String browsable = "android.intent.category.BROWSABLE";
        String view = "android.intent.action.VIEW";

        Intent intent = new Intent(view);
        intent.addCategory(default_browser);
        intent.addCategory(browsable);
        Uri uri = Uri.parse("http://");
        intent.setDataAndType(uri, null);

        // 找出手机当前安装的所有浏览器程序
        List<ResolveInfo> resolveInfoList = context.getPackageManager()
                .queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
        if (resolveInfoList.size() > 0) {
            ActivityInfo activityInfo = resolveInfoList.get(0).activityInfo;
            String packageName = activityInfo.packageName;
            String className = activityInfo.name;
            return packageName;
        } else {
            return null;
        }
    }


    public static String getImei(Context context) {
        TelephonyManager tm = (TelephonyManager) (context
                .getSystemService(Context.TELEPHONY_SERVICE));
        String imei = tm.getDeviceId();
        return imei;
    }


    public static String getIp(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        String ip = "";
        if (wifiManager != null) {
            try {
                if (CommonUtil.checkWifiState(context)) {
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    int ipAddress = wifiInfo.getIpAddress();
                    ip = intToIp(ipAddress);
                } else {
                    Log.e("OOAgent", "please add uses-permission for android.permission.ACCESS_WIFI_STATE");
                }
            } catch (Exception e) {
                Log.e("OOAgent", "please add uses-permission for android.permission.ACCESS_WIFI_STATE");
            }

        }
        return ip;
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    public static String getMac(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        String macAddress = "";
        if (wifiManager != null) {
            try {
                if (CommonUtil.checkWifiState(context)) {
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    int ipAddress = wifiInfo.getIpAddress();
                    macAddress = wifiInfo.getMacAddress();
                    macAddress = macAddress.replaceAll(":", "-");
                } else {
                    Log.e("OOAgent", "please add uses-permission for android.permission.ACCESS_WIFI_STATE");
                }
            } catch (Exception e) {
                Log.e("OOAgent", "please add uses-permission for android.permission.ACCESS_WIFI_STATE");
            }

        } else {
            try {
                //获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
                byte[] mac = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();

                //下面代码是把mac地址拼装成String
                StringBuffer sb = new StringBuffer();

                if (mac != null && mac.length > 0)
                    for (int i = 0; i < mac.length; i++) {
                        if (i != 0) {
                            sb.append("-");
                        }
                        //mac[i] & 0xFF 是为了把byte转化为正整数
                        String s = Integer.toHexString(mac[i] & 0xFF);
                        sb.append(s.length() == 1 ? 0 + s : s);
                    }
                //把字符串所有小写字母改为大写成为正规的mac地址并返回
                macAddress = sb.toString().toUpperCase();
                macAddress = macAddress.replaceAll(":", "-");
            } catch (SocketException ex) {
                CommonUtil.printLog("error", "info: " + ex);
            } catch (UnknownHostException e) {
                CommonUtil.printLog("error", "info: " + e);
            } catch (Exception e) {
                CommonUtil.printLog("error", "info: " + e);
            }
        }
        return macAddress;
    }

    public static String getDeviceToken(Context context) {
        return "";
    }

    public static String getIdfa(Context context) {
        return "";
    }


}
