package com.za.common.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaDrm;
import android.os.Build;
import android.provider.Settings;

import com.blankj.utilcode.util.SPUtils;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * 设备唯一标识
 * 顺序为：Android_ID->DRM_ID->UUID
 */
public class DeviceUtil {
    public static String getAndroidId(Context context) {
        String deviceId = SPUtils.getInstance().getString("deviceId");
        if (deviceId == null || deviceId.isEmpty()) {
            @SuppressLint("HardwareIds") String temp = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            if (temp == null || temp.isEmpty() || temp.replace("0", "").isEmpty()) {
                temp = getDrmId();
            }
            SPUtils.getInstance().put("deviceId", temp);
            return temp;
        }
        return deviceId;
    }

    private static String getDrmId() {
        String sRet = "";
        UUID WIDEVINE_UUID = new UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L);
        MediaDrm mediaDrm = null;
        try {
            mediaDrm = new MediaDrm(WIDEVINE_UUID);
            byte[] widevineId = mediaDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID);

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(widevineId);

            sRet = bytesToHex(md.digest()); //we convert byte[] to hex for our purposes
        } catch (Exception e) {
            //WIDEVINE is not available
        } finally {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                if (null != mediaDrm) {
                    mediaDrm.close();
                }
            } else {
                if (null != mediaDrm) {
                    mediaDrm.release();
                }
            }
        }

        if (sRet.isEmpty()) {
            sRet = WIDEVINE_UUID.toString().replace("-", "");
        }
        return sRet;
    }

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
}

