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

import android.content.Context;

import com.oo.seex.oo_statistics_lib.utils.utdid.utils.PhoneInfiUtils;
import com.oo.seex.oo_statistics_lib.utils.utdid.utils.StringUtils;

import java.util.zip.Adler32;

public class DeviceInfo {
    private static Device mDevice = null;
    static String HMAC_KEY = "d6fc3a4a06adbde89223bvefedc24fecde188aaa9161";
    static final Object CREATE_DEVICE_METADATA_LOCK = new Object();
    static final byte UTDID_VERSION_CODE = 1;

    public DeviceInfo() {
    }

    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 static Device _initDeviceMetadata(Context aContext) {
        if(aContext != null) {
            new Device();
            Object var2 = CREATE_DEVICE_METADATA_LOCK;
            synchronized(CREATE_DEVICE_METADATA_LOCK) {
                String utdid = UTUtdid.instance(aContext).getValue();
                if(!StringUtils.isEmpty(utdid)) {
                    if(utdid.endsWith("\n")) {
                        utdid = utdid.substring(0, utdid.length() - 1);
                    }

                    Device device = new Device();
                    long timestamp = System.currentTimeMillis();
                    String imei = PhoneInfiUtils.getImei(aContext);
                    String imsi = PhoneInfiUtils.getImsi(aContext);
                    device.setDeviceId(imei);
                    device.setImei(imei);
                    device.setCreateTimestamp(timestamp);
                    device.setImsi(imsi);
                    device.setUtdid(utdid);
                    device.setCheckSum(getMetadataCheckSum(device));
                    return device;
                }
            }
        }

        return null;
    }

    public static synchronized Device getDevice(Context context) {
        if(mDevice != null) {
            return mDevice;
        } else if(context != null) {
            Device device = _initDeviceMetadata(context);
            mDevice = device;
            return device;
        } else {
            return null;
        }
    }
}
