package org.cocos2dx.javascript.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import org.cocos2dx.javascript.thirdSdk.oaid.OaidHelper;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

public class DeviceUtil {


    /**
     * 是否支持Oaid
     */
    private static boolean isSupportOaid = true;
    private static int errorCode;
    public  static String oaid;

    public static String getErrorCode() {
        return String.valueOf(errorCode);
    }

    public static boolean isSupportOaid() {
        return isSupportOaid;
    }

    public static void setIsSupportOaid(boolean isSupportOaid) {
        DeviceUtil.isSupportOaid = isSupportOaid;
    }

    public static void setIsSupportOaid(boolean isSupportOaid, int ErrorCode) {
        DeviceUtil.isSupportOaid = isSupportOaid;
        DeviceUtil.errorCode = ErrorCode;
    }

    /**预先获取Oaid*/
    public static void preGetOaid(Context context) {
        Log.d("[DevicesUtil] ids","1");
        //获取OAID等设备标识符
        OaidHelper oaidHelper = new OaidHelper(appIdsUpdater);
        oaidHelper.getDeviceIds(context);
    }

    public static OaidHelper.AppIdsUpdater appIdsUpdater = new OaidHelper.AppIdsUpdater() {
        @Override
        public void OnIdsAvalid(@NonNull String ids) {
            Log.d("[DevicesUtil] ids2: ", ids);
            DeviceUtil.oaid = ids;
        }
    };

    /**
     * 获取Oaid
     */
    public static String getOaid() {
        String idfa;
        if (DeviceUtil.isSupportOaid()) {
            idfa = DeviceUtil.oaid;
        } else {
            idfa = null;
            // idfa = "获取失败，ErrorCode: " + DEV.getErrorCode();
            Log.d("获取失败，ErrorCode",DeviceUtil.getErrorCode());
        }
        return idfa;
    }

    //-------- 获取Imei --------
    public static String getImei(Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            imei = tm.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imei;
    }

    //-------- 获取mac地址--------
    public static String getMac(Context context) {
        String strMac = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Log.e("=====", "6.0以下");
            Toast.makeText(context, "6.0以下", Toast.LENGTH_SHORT).show();
            strMac = getLocalMacAddressFromWifiInfo(context);
            return strMac;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.e("=====", "7.0以上");
            strMac = getMac();
//            Log.e("=====",Build.VERSION.SDK_INT +"");
//            Log.e("=====",strMac);
//            String  strMac1= getNewMac();
//            Log.e("=====",strMac1);
            return strMac;
        }
        return "02:00:00:00:00:00";
    }

    /**
     * 这是使用adb shell命令来获取mac地址的方式(可获取7.0以上 亲测)
     * @description
     * @return
     */
    public static String getMac() {
        String macSerial = null;
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("ip addr");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    if (macSerial.indexOf("link/ether") != -1) {
                        break;
                    }
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
//        Log.d("vvvvvvvvv  ", "getMac: " + macSerial);
        String mac = "";
        if (macSerial.split(" ").length >= 2) {
            mac = macSerial.split(" ")[1];
        }
        return mac;
    }

    /**
     * 根据wifi信息获取本地mac
     * @param context
     * @return
     */
    public static String getLocalMacAddressFromWifiInfo(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo winfo = wifi.getConnectionInfo();
        String mac = winfo.getMacAddress();
        return mac;
    }

    // Android Id
    public static String getAndroidId(Context context) {
        String androidId = Settings.Secure.getString(
                context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    /**
     * 通过网络接口取 (7.0以上可用 亲测)（暂时不用）
     * @return
     */
    private static String getNewMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) 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;
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * get App versionName
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
