package com.oo.seex.oo_statistics_lib.utils.utdid.Device;

import android.content.Context;

import com.oo.seex.oo_statistics_lib.utils.utdid.core.PersistentConfiguration;
import com.oo.seex.oo_statistics_lib.utils.utdid.utils.Base64;
import com.oo.seex.oo_statistics_lib.utils.utdid.utils.IntUtils;
import com.oo.seex.oo_statistics_lib.utils.utdid.utils.PhoneInfiUtils;
import com.oo.seex.oo_statistics_lib.utils.utdid.utils.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Adler32;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class UTUtdid {
    private static final String HMAC_KEY = "d6fc3a4a06adbde89223bvefedc24fecde188aaa9161";
    private Context mContext = null;
    private static final Object CREATE_LOCK = new Object();
    private static UTUtdid s_umutdid = null;
    private String mUtdid = null;
    private UTUtdidHelper mUtdidHelper = null;
    private String mCBKey = "xx_utdid_key";
    private String mCBDomain = "xx_utdid_domain";
    static final String UM_SETTINGS_STORAGE = "dxCRMxhQkdGePGnp";
    static final String UM_SETTINGS_STORAGE_NEW = "mqBRboGZkQPcAkyk";
    private PersistentConfiguration mPC = null;
    private static final String S_LOCAL_STORAGE_NAME = ".DataStorage";
    private static final String S_LOCAL_STORAGE_KEY = "ContextData";
    private PersistentConfiguration mTaoPC = null;
    private static final String S_GLOBAL_PERSISTENT_CONFIG_DIR;
    private static final String S_GLOBAL_PERSISTENT_CONFIG_KEY = "Alvin2";
    private Pattern mPattern = Pattern.compile("[^0-9a-zA-Z=/+]+");

    public UTUtdid(Context context) {
        this.mContext = context;
        this.mTaoPC = new PersistentConfiguration(context, S_GLOBAL_PERSISTENT_CONFIG_DIR, "Alvin2", false, true);
        this.mPC = new PersistentConfiguration(context, ".DataStorage", "ContextData", false, true);
        this.mUtdidHelper = new UTUtdidHelper();
        this.mCBKey = String.format("K_%d", new Object[]{Integer.valueOf(StringUtils.hashCode(this.mCBKey))});
        this.mCBDomain = String.format("D_%d", new Object[]{Integer.valueOf(StringUtils.hashCode(this.mCBDomain))});
    }

    public static UTUtdid instance(Context context) {
        if(context != null && s_umutdid == null) {
            Object var1 = CREATE_LOCK;
            synchronized(CREATE_LOCK) {
                if(s_umutdid == null) {
                    s_umutdid = new UTUtdid(context);
                }
            }
        }

        return s_umutdid;
    }

    static long getMetadataCheckSum(Device device) {
        if(device != null) {
            String checkSumContent = String.format("%s%s%s%s%s", new Object[]{device.getUtdid(), device.getDeviceId(), Long.valueOf(device.getCreateTimestamp()), device.getImsi(), device.getImei()});
            if(!StringUtils.isEmpty(checkSumContent)) {
                Adler32 adler32 = new Adler32();
                adler32.reset();
                adler32.update(checkSumContent.getBytes());
                long checkSum = adler32.getValue();
                return checkSum;
            }
        }

        return 0L;
    }

    private void saveUtdidToTaoPPC(String pUtdid) {
        if(this.isValidUTDID(pUtdid)) {
            if(pUtdid.endsWith("\n")) {
                pUtdid = pUtdid.substring(0, pUtdid.length() - 1);
            }

            if(pUtdid.length() == 24 && this.mTaoPC != null) {
                String lUTDID = this.mTaoPC.getString("UTDID");
                String lIMEI = this.mTaoPC.getString("EI");
                if(StringUtils.isEmpty(lIMEI)) {
                    lIMEI = PhoneInfiUtils.getImei(this.mContext);
                }

                String lIMSI = this.mTaoPC.getString("SI");
                if(StringUtils.isEmpty(lIMSI)) {
                    lIMSI = PhoneInfiUtils.getImsi(this.mContext);
                }

                String lDID = this.mTaoPC.getString("DID");
                if(StringUtils.isEmpty(lDID)) {
                    lDID = lIMEI;
                }

                if(null == lUTDID || !lUTDID.equals(pUtdid)) {
                    Device lD = new Device();
                    lD.setImei(lIMEI);
                    lD.setImsi(lIMSI);
                    lD.setUtdid(pUtdid);
                    lD.setDeviceId(lDID);
                    lD.setCreateTimestamp(System.currentTimeMillis());
                    this.mTaoPC.putString("UTDID", pUtdid);
                    this.mTaoPC.putString("EI", lD.getImei());
                    this.mTaoPC.putString("SI", lD.getImsi());
                    this.mTaoPC.putString("DID", lD.getDeviceId());
                    this.mTaoPC.putLong("timestamp", lD.getCreateTimestamp());
                    this.mTaoPC.putLong("S", getMetadataCheckSum(lD));
                    this.mTaoPC.commit();
                }
            }
        }

    }

    private void saveUtdidToLocalStorage(String pPackedUtdid) {
        if(null != pPackedUtdid && null != this.mPC) {
            String lPackedUtdid = this.mPC.getString(this.mCBKey);
            if(!pPackedUtdid.equals(lPackedUtdid)) {
                this.mPC.putString(this.mCBKey, pPackedUtdid);
                this.mPC.commit();
            }
        }

    }

    private void saveUtdidToNewSettings(String lUtdid) {
        int lPermission = this.mContext.checkCallingOrSelfPermission("android.permission.WRITE_SETTINGS");
        if(0 == lPermission && this.isValidUTDID(lUtdid)) {
            if(lUtdid.endsWith("\n")) {
                lUtdid = lUtdid.substring(0, lUtdid.length() - 1);
            }

            if(24 == lUtdid.length()) {
                String data = android.provider.Settings.System.getString(this.mContext.getContentResolver(), "mqBRboGZkQPcAkyk");
                if(!this.isValidUTDID(data)) {
                    android.provider.Settings.System.putString(this.mContext.getContentResolver(), "mqBRboGZkQPcAkyk", lUtdid);
                }
            }
        }

    }

    private void syncUTDIDToSettings(String pPackedUtdid) {
        String data = android.provider.Settings.System.getString(this.mContext.getContentResolver(), "dxCRMxhQkdGePGnp");
        if(!pPackedUtdid.equals(data)) {
            android.provider.Settings.System.putString(this.mContext.getContentResolver(), "dxCRMxhQkdGePGnp", pPackedUtdid);
        }

    }

    private void saveUtdidToSettings(String lPackedUtdid) {
        int lPermission = this.mContext.checkCallingOrSelfPermission("android.permission.WRITE_SETTINGS");
        if(0 == lPermission && null != lPackedUtdid) {
            this.syncUTDIDToSettings(lPackedUtdid);
        }

    }

    private String getUtdidFromTaoPPC() {
        if(null != this.mTaoPC) {
            String lUTDID = this.mTaoPC.getString("UTDID");
            if(!StringUtils.isEmpty(lUTDID)) {
                String lPackedUtdid = this.mUtdidHelper.packUtdidStr(lUTDID);
                if(null != lPackedUtdid) {
                    return lUTDID;
                }
            }
        }

        return null;
    }

    private boolean isValidUTDID(String pUTDID) {
        if(null != pUTDID) {
            if(pUTDID.endsWith("\n")) {
                pUTDID = pUTDID.substring(0, pUTDID.length() - 1);
            }

            if(24 == pUTDID.length()) {
                Matcher lMatcher = this.mPattern.matcher(pUTDID);
                if(!lMatcher.find()) {
                    return true;
                }
            }
        }

        return false;
    }

    public synchronized String getValue() {
        if(null != this.mUtdid) {
            return this.mUtdid;
        } else {
            String lNewSettingsUtdid = android.provider.Settings.System.getString(this.mContext.getContentResolver(), "mqBRboGZkQPcAkyk");
            if(this.isValidUTDID(lNewSettingsUtdid)) {
                return lNewSettingsUtdid;
            } else {
                UTUtdidHelper2 lHelper2 = new UTUtdidHelper2();
                boolean lNeedUpdateSettings = false;
                String data = android.provider.Settings.System.getString(this.mContext.getContentResolver(), "dxCRMxhQkdGePGnp");
                String lSUtdid;
                String lContent;
                String e;
                if(!StringUtils.isEmpty(data)) {
                    lSUtdid = lHelper2.dePackWithBase64(data);
                    if(this.isValidUTDID(lSUtdid)) {
                        this.saveUtdidToNewSettings(lSUtdid);
                        return lSUtdid;
                    }

                    lContent = lHelper2.dePack(data);
                    if(this.isValidUTDID(lContent)) {
                        e = this.mUtdidHelper.packUtdidStr(lContent);
                        if(!StringUtils.isEmpty(e)) {
                            this.saveUtdidToSettings(e);
                            data = android.provider.Settings.System.getString(this.mContext.getContentResolver(), "dxCRMxhQkdGePGnp");
                        }
                    }

                    e = this.mUtdidHelper.dePack(data);
                    if(this.isValidUTDID(e)) {
                        this.mUtdid = e;
                        this.saveUtdidToTaoPPC(e);
                        this.saveUtdidToLocalStorage(data);
                        this.saveUtdidToNewSettings(this.mUtdid);
                        return this.mUtdid;
                    }
                } else {
                    lNeedUpdateSettings = true;
                }

                lSUtdid = this.getUtdidFromTaoPPC();
                if(this.isValidUTDID(lSUtdid)) {
                    lContent = this.mUtdidHelper.packUtdidStr(lSUtdid);
                    if(lNeedUpdateSettings) {
                        this.saveUtdidToSettings(lContent);
                    }

                    this.saveUtdidToNewSettings(lSUtdid);
                    this.saveUtdidToLocalStorage(lContent);
                    this.mUtdid = lSUtdid;
                    return lSUtdid;
                } else {
                    lContent = this.mPC.getString(this.mCBKey);
                    String lPackedUtdid;
                    if(!StringUtils.isEmpty(lContent)) {
                        e = lHelper2.dePack(lContent);
                        if(!this.isValidUTDID(e)) {
                            e = this.mUtdidHelper.dePack(lContent);
                        }

                        if(this.isValidUTDID(e)) {
                            lPackedUtdid = this.mUtdidHelper.packUtdidStr(e);
                            if(!StringUtils.isEmpty(e)) {
                                this.mUtdid = e;
                                if(lNeedUpdateSettings) {
                                    this.saveUtdidToSettings(lPackedUtdid);
                                }

                                this.saveUtdidToTaoPPC(this.mUtdid);
                                return this.mUtdid;
                            }
                        }
                    }

                    try {
                        byte[] e1 = this._generateUtdid();
                        if(null != e1) {
                            this.mUtdid = Base64.encodeToString(e1, 2);
                            this.saveUtdidToTaoPPC(this.mUtdid);
                            lPackedUtdid = this.mUtdidHelper.pack(e1);
                            if(null != lPackedUtdid) {
                                if(lNeedUpdateSettings) {
                                    this.saveUtdidToSettings(lPackedUtdid);
                                }

                                this.saveUtdidToLocalStorage(lPackedUtdid);
                            }

                            return this.mUtdid;
                        }
                    } catch (Exception var9) {
                        var9.printStackTrace();
                    }

                    return null;
                }
            }
        }
    }

    private final byte[] _generateUtdid() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int timestamp = (int)(System.currentTimeMillis() / 1000L);
        int uniqueID = (new Random()).nextInt();
        byte version = 3;
        byte reserve = 0;
        byte[] bTimestamp = IntUtils.getBytes(timestamp);
        byte[] bUniqueID = IntUtils.getBytes(uniqueID);
        baos.write(bTimestamp, 0, 4);
        baos.write(bUniqueID, 0, 4);
        baos.write(version);
        baos.write(reserve);
        String imei = null;

        try {
            imei = PhoneInfiUtils.getImei(this.mContext);
        } catch (Exception var13) {
            imei = "" + (new Random()).nextInt();
        }

        int hashCode = StringUtils.hashCode(imei);
        byte[] bHashCode = IntUtils.getBytes(hashCode);
        baos.write(bHashCode, 0, 4);
        String hmac = "";
        hmac = _calcHmac(baos.toByteArray());
        byte[] bCheckSum = IntUtils.getBytes(StringUtils.hashCode(hmac));
        baos.write(bCheckSum);
        return baos.toByteArray();
    }

    private static String _calcHmac(byte[] src) throws Exception {
        String key = "d6fc3a4a06adbde89223bvefedc24fecde188aaa9161";
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec sk = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
        mac.init(sk);
        byte[] result = mac.doFinal(src);
        return Base64.encodeToString(result, 2);
    }

    static {
        S_GLOBAL_PERSISTENT_CONFIG_DIR = ".UTSystemConfig" + File.separator + "Global";
    }
}
