package cn.ninegame.ad.demo.util;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;


/**
 * Created by guosen.lgs@alibaba-inc.com on 12/26/16.
 */
public class PhoneInfoUtil {

    private static final String TAG = PhoneInfoUtil.class.getSimpleName();


    /**
     * 缓存获取的结果，不要每次都从系统api获取，避免对隐私信息的获取频率过高导致违规
     */
    public static class Delegate {
        String imei = "";
        String imsi = "";
        String androidId = "";
        String mac = "";
        String oaid = "";
        Location location;
        long getLocationTime;

        public String getIMEI() {
            if (imei != null) {
                return imei;
            }

            if (imei == null && AppContextHelper.hasReadPhonePermission()) {
                try {
                    TelephonyManager telephonyManager = AppContextHelper.telephonyManager();
                    imei = telephonyManager.getDeviceId();
                } catch (Exception ignore) {
                }
                if (TextUtils.isEmpty(imei)) {
                    imei = "";
                }
            }

            return imei;
        }

        public String getIMSI() {
            if (imsi != null) {
                return imsi;
            }

            if (imsi == null && AppContextHelper.hasReadPhonePermission()) {
                try {
                    TelephonyManager telephonyManager = AppContextHelper.telephonyManager();
                    imsi = telephonyManager.getSubscriberId();
                } catch (Exception ignore) {
                }
                if (TextUtils.isEmpty(imsi)) {
                    imsi = "";
                }
            }

            return imsi;
        }

        public String getMAC() {
            if (mac != null) {
                return mac;
            }
            if (mac == null && AppContextHelper.hasReadPhonePermission()) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    mac = getMacFromWifi();
                } else {
                    mac = getMacFromNetwork();
                }
                if (TextUtils.isEmpty(mac)) {
                    mac = "";
                }
            }
            return mac;
        }

        private static String getMacFromWifi() {
            String macAddress = "";
            try {
                WifiManager wifiMgr = AppContextHelper.wifiManager();
                if (wifiMgr != null) {
                    WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                    if (wifiInfo != null) {
                        macAddress = wifiInfo.getMacAddress();
                    }
                }
            } catch (Exception ignore) {
            }
            return macAddress;
        }

        private static String getMacFromNetwork() {
            String macAddress = "";
            try {
                Enumeration<NetworkInterface> items = NetworkInterface.getNetworkInterfaces();
                if (items != null) {
                    List<NetworkInterface> all = Collections.list(items);
                    for (NetworkInterface nif : all) {
                        if (!"wlan0".equalsIgnoreCase(nif.getName())) {
                            continue;
                        }

                        byte[] macBytes = nif.getHardwareAddress();
                        if (macBytes == null) {
                            return macAddress;
                        }
                        macAddress = getMacInHex(macBytes);
                        break;
                    }
                }
            } catch (Exception ignore) {
            }
            return macAddress;
        }

        static final String HEXES = "0123456789ABCDEF";

        private static String getMacInHex(byte[] raw) {
            if (raw == null) {
                return "";
            }

            final StringBuilder hex = new StringBuilder(2 * raw.length);
            for (final byte b : raw) {
                hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F))).append(':');
            }

            if (hex.length() > 0) {
                hex.deleteCharAt(hex.length() - 1);
            }
            return hex.toString();
        }


        public String getAndroidID() {
            if (androidId != null) {
                return androidId;
            }
            try {
                androidId = Settings.Secure.getString(AppContextHelper.contentResolver(), Settings.Secure.ANDROID_ID);
            } catch (Exception ignore) {
            }
            if (TextUtils.isEmpty(androidId)) {
                androidId = "";
            }
            return androidId;
        }

        public String getOaid() {
            if (oaid != null) {
                return oaid;
            }
            // 请自己实获取取oaid的方法
            return "oaid-test";
        }

        @Nullable
        public Location getGpsLocation() {
            // 地理位置信息，不需要过于频繁，请按照业务场景进行调整
            if (location != null && System.currentTimeMillis() - getLocationTime > 30 * 60 * 1000) {
                return location;
            }

            Location lastKnowLocation = null;
            try {
                LocationManager locationManager = (LocationManager) AppContextHelper.appContext().getSystemService(Context.LOCATION_SERVICE);
                if (locationManager != null) {
                    lastKnowLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    getLocationTime = System.currentTimeMillis();
                }
                return lastKnowLocation;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return lastKnowLocation;
        }

    }

    /**
     * For easier mocking the phone state data, we use a delegate class here.
     */
    private static Delegate mDelegate = new Delegate();

    private static final String CLASS_NAME = "PhoneInfoUtil";

    /**
     * 获取imei
     *
     * @return
     */
    public static String getIMEI() {
        return mDelegate.getIMEI();
    }


    /**
     * 获取mac地址
     *
     * @return
     */
    public static String getMAC() {
        return mDelegate.getMAC();
    }

    /**
     * 获取android_id
     *
     * @return
     */
    public static String getAndroidId() {
        return mDelegate.getAndroidID();
    }

    /**
     * 获取oaid
     *
     * @return
     */
    public static String getOaid() {
        return mDelegate.getOaid();
    }

    /**
     * 获取位置信息
     *
     * @return
     */
    public static Location getGpsLocation() {
        return mDelegate.getGpsLocation();
    }


}
