package com.stm.asset.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.io.IOException;
import java.util.UUID;

public class DeviceUuidFactory {
	
	private static final String PREFS_FILE = "device_id.xml";
	private static final String PREFS_DEVICE_ID = "device_id";
	private static DeviceUuidFactory instance = new DeviceUuidFactory();
	private static UUID uuid;
	
	private DeviceUuidFactory() {}
	
	public static DeviceUuidFactory getInstance() {
		if (instance == null) {
			instance = new DeviceUuidFactory();
		}
		return instance;
	}
	
	public String getDeviceId(Context context) {
		if (uuid == null) {
			synchronized(DeviceUuidFactory.class) {
				if (uuid == null) {
					SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
					String id = prefs.getString(PREFS_DEVICE_ID, null);
					if (id != null) {
						uuid = UUID.fromString(id);
					} else {
						String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
						try {
							if (!"9774d56d682e549c".equals(androidId) && androidId != null) {
								uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
							} else {
								String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();  
								uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
							}
						} catch (SecurityException | IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return uuid.toString();
	}

}
