package com.atmob.system_share;

import android.content.Context;
import android.net.Uri;
import android.os.Build;

import java.io.File;
import java.lang.reflect.Method;

public class UriUtil {
    public static Uri getFileUri(Context context, File file) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            return Uri.fromFile(file);
        }
        Uri uri = getFileUriFromXFileProvider(context, file);
        if (uri == null) {
            uri = getFileUriFromV4FileProvider(context, file);
        }
        return uri;
    }

    private static Uri getFileUriFromV4FileProvider(Context context, File file) {
        try {
            Class<?> v4FileProvider = Class.forName("android.support.v4.content.FileProvider");
            Method getUriForFile = v4FileProvider.getMethod("getUriForFile", Context.class, String.class, File.class);
            return (Uri) getUriForFile.invoke(null, context, context.getPackageName() + ".fileprovider", file);
        } catch (Exception e) {
            return null;
        }
    }

    private static Uri getFileUriFromXFileProvider(Context context, File file) {
        try {
            Class<?> xFileProvider = Class.forName("androidx.core.content.FileProvider");
            Method getUriForFile = xFileProvider.getMethod("getUriForFile", Context.class, String.class, File.class);
            return (Uri) getUriForFile.invoke(null, context, context.getPackageName() + ".fileprovider", file);
        } catch (Exception e) {
            return null;
        }
    }
}
