package ai.guiji.duix.sample.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.text.TextUtils;

import java.util.UUID;

public class DeviceUtils {

    public static String getVersionName(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "Unknown";
        }
    }

    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

//    public static boolean isWifi(Context mContext) {
//        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
//                .getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo info = null;
//        if (connectivityManager != null) {
//            info = connectivityManager.getActiveNetworkInfo();
//        }
//        return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
//    }

    private static String getAndroidID(Context context) {
        return Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    private static String getDeviceUUid(Context context) {
        String androidId = DeviceUtils.getAndroidID(context);
        if (TextUtils.isEmpty(androidId)) {
            return null;
        }
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) androidId.hashCode() << 32));
        return deviceUuid.toString();
    }

    private static String getAppUUid(Context context) {
        SharedPreferences preferences = context.getSharedPreferences("android_uuid", Context.MODE_PRIVATE);
        String uuid = preferences.getString("UUID", null);
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            preferences.edit().putString("UUID", uuid).apply();
        }
        return uuid;
    }

    public static String getUUID(Context context) {
        String uuid = getDeviceUUid(context);
        if (TextUtils.isEmpty(uuid)) {
            uuid = getAppUUid(context);
        }
        return uuid;
    }
}
