package com.kfzs.duanduan.utils.dlg;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.kf.utils.DeviceIDFactory;

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

/**
 * @ Created by Dlg
 * @ <p>TiTle:  DeviceUtils</p>
 * @ <p>Description:获取各种硬件信息</p>
 * @ date:  2017/10/29 11:48
 * @ QQ:    315096953
 */

public class DeviceUtils {

    private Context mContext;
    private TelephonyManager phone;
    private WifiManager wifi;

    public DeviceUtils(Context context) {
        phone = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mContext = context;
    }


    public String getWifiMac() {
        return getLocalMacAddress();
    }

    /**
     * 获取本机MAC地址
     *
     * @return
     */
    private String getLocalMacAddress() {
        String wlan = DeviceIDFactory.getDeviceIDByMac();
        if (TextUtils.isEmpty(wlan)) {
            wlan = getMacAddr();
        }
        if (TextUtils.isEmpty(wlan)) {
            wlan = DeviceIDFactory.getUUID(mContext);
            // Max size 16
            if (wlan.length() > 16) {
                wlan = wlan.substring(0, 16);
            }
        }
        return wlan;
    }

    public static String getMacAddr() {
        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 "";
                }

                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 ignored) {
        }
        return "";
    }


    public String getIMEI() {
        try {
            return phone.getDeviceId();
        } catch (Exception e) {
            return "";
        }
    }

    public String getIMEIRnd() {
        String tmp = getLastIMEI();
        if (tmp.length() > 10) {
            return tmp;
        }
        tmp = getIMEI();
        if (tmp == null) {
            tmp = new Random().nextInt(999999) + "";
            while (tmp.length() < 7) {
                tmp = tmp + "0";
            }
            tmp = tmp + new Random().nextInt(999999);
            while (tmp.length() < 15) {
                tmp = tmp + "0";
            }

            String rand = new Random().nextInt(999999) + "";
            while (rand.length() < 6) {
                rand = "0" + rand;
            }
            tmp = tmp.substring(0, 8) + rand;
            char[] imeiChar = tmp.toCharArray();
            int resultInt = 0;
            for (int i = 0; i < imeiChar.length; i++) {
                int a = Integer.parseInt(String.valueOf(imeiChar[i]));
                i++;
                final int temp = Integer.parseInt(String.valueOf(imeiChar[i])) * 2;
                final int b = temp < 10 ? temp : temp - 9;
                resultInt += a + b;
            }
            resultInt %= 10;
            resultInt = resultInt == 0 ? 0 : 10 - resultInt;
            tmp = tmp + resultInt;
        }
        saveLastIMEI(tmp);
        return tmp;
    }

    private String getLastIMEI() {
        String iemi = new Configer().getString(Configer.IMEI, "");
        return iemi == null ? "" : iemi;
    }

    private void saveLastIMEI(String iemi) {
        new Configer().put(Configer.IMEI, iemi).commit();
    }

    public String getIMSI(Context context) {
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return "";
            }
            return phone.getSubscriberId();
        }catch (Exception e){
            return "";
        }
    }

    public String getManufacture() {
        return android.os.Build.MANUFACTURER + "";
    }

    /**
     * 品牌和机型两上
     *
     * @return
     */
    public String getModel() {
        return android.os.Build.BRAND + android.os.Build.MODEL;
    }

    public String getWifiSSID() {
        return wifi.getConnectionInfo().getSSID() + "";
    }

    public String getWifiBSSID() {
        return wifi.getConnectionInfo().getBSSID() + "";
    }

    public int getAppVersionCode() {
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * android id
     */
    public String getAndroidId() {
        return Settings.Secure.getString(mContext.getContentResolver(),
                Settings.Secure.ANDROID_ID);
    }

}
