package com.mr.flutter.plugin.filepicker;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.provider.DocumentsContract;
import android.webkit.MimeTypeMap;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.gms.measurement.internal.u1;
import defpackage.e;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/* JADX INFO: loaded from: classes.dex */
public abstract class d {
    public static Uri a(Uri uri, int i10, Context context) {
        try {
            InputStream inputStreamOpenInputStream = context.getContentResolver().openInputStream(uri);
            try {
                File fileB = b();
                Bitmap bitmapDecodeStream = BitmapFactory.decodeStream(inputStreamOpenInputStream);
                FileOutputStream fileOutputStream = new FileOutputStream(fileB);
                bitmapDecodeStream.compress(Bitmap.CompressFormat.JPEG, i10, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
                Uri uriFromFile = Uri.fromFile(fileB);
                if (inputStreamOpenInputStream != null) {
                    inputStreamOpenInputStream.close();
                }
                return uriFromFile;
            } finally {
            }
        } catch (FileNotFoundException e10) {
            throw new RuntimeException(e10);
        } catch (IOException e11) {
            throw new RuntimeException(e11);
        }
    }

    public static File b() {
        return File.createTempFile(u1.k("JPEG_", new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()), "_"), ".jpg", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
    }

    public static String c(Context context, Uri uri) {
        String string = null;
        try {
            if (uri.getScheme().equals("content")) {
                Cursor cursorQuery = context.getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null);
                if (cursorQuery != null) {
                    try {
                        if (cursorQuery.moveToFirst()) {
                            string = cursorQuery.getString(cursorQuery.getColumnIndexOrThrow("_display_name"));
                        }
                    } finally {
                        cursorQuery.close();
                    }
                }
            }
            if (string != null) {
                return string;
            }
            String path = uri.getPath();
            int iLastIndexOf = path.lastIndexOf(47);
            return iLastIndexOf != -1 ? path.substring(iLastIndexOf + 1) : path;
        } catch (Exception e10) {
            e10.toString();
            return string;
        }
    }

    public static String[] d(ArrayList arrayList) {
        if (arrayList == null || arrayList.isEmpty()) {
            return null;
        }
        ArrayList arrayList2 = new ArrayList();
        for (int i10 = 0; i10 < arrayList.size(); i10++) {
            String mimeTypeFromExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension((String) arrayList.get(i10));
            if (mimeTypeFromExtension == null) {
            } else {
                arrayList2.add(mimeTypeFromExtension);
            }
        }
        arrayList2.toString();
        return (String[]) arrayList2.toArray(new String[0]);
    }

    public static a e(Activity activity, Uri uri, boolean z10) {
        FileOutputStream fileOutputStream;
        uri.toString();
        x4.d dVar = new x4.d();
        String strC = c(activity, uri);
        StringBuilder sb = new StringBuilder();
        sb.append(activity.getCacheDir().getAbsolutePath());
        sb.append("/file_picker/");
        sb.append(System.currentTimeMillis());
        sb.append("/");
        sb.append(strC != null ? strC : "unamed");
        String string = sb.toString();
        File file = new File(string);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                fileOutputStream = new FileOutputStream(string);
                try {
                    try {
                        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                        InputStream inputStreamOpenInputStream = activity.getContentResolver().openInputStream(uri);
                        byte[] bArr = new byte[8192];
                        while (true) {
                            int i10 = inputStreamOpenInputStream.read(bArr);
                            if (i10 < 0) {
                                break;
                            }
                            bufferedOutputStream.write(bArr, 0, i10);
                        }
                        bufferedOutputStream.flush();
                        fileOutputStream.getFD().sync();
                    } catch (Exception e10) {
                        e = e10;
                        try {
                            fileOutputStream.close();
                            e.getMessage();
                            return null;
                        } catch (IOException | NullPointerException unused) {
                            e.getMessage();
                            return null;
                        }
                    }
                } catch (Throwable th) {
                    fileOutputStream.getFD().sync();
                    throw th;
                }
            } catch (Exception e11) {
                e = e11;
                fileOutputStream = null;
            }
        }
        if (z10) {
            try {
                int length = (int) file.length();
                byte[] bArr2 = new byte[length];
                try {
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                    bufferedInputStream.read(bArr2, 0, length);
                    bufferedInputStream.close();
                } catch (FileNotFoundException e12) {
                    e12.getMessage();
                } catch (IOException e13) {
                    e13.getMessage();
                }
                dVar.f34721b = bArr2;
            } catch (Exception e14) {
                e14.toString();
            }
        }
        dVar.f34722c = string;
        dVar.f34723d = strC;
        dVar.f34724e = uri;
        long j10 = Long.parseLong(String.valueOf(file.length()));
        dVar.f34720a = j10;
        return new a((String) dVar.f34722c, (String) dVar.f34723d, (Uri) dVar.f34724e, j10, (byte[]) dVar.f34721b);
    }

    public static void f(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            for (File file2 : file.listFiles()) {
                f(file2);
            }
        }
        file.delete();
    }

    @Nullable
    private static String getDirectoryPath(Class<?> cls, Object obj) {
        if (Build.VERSION.SDK_INT < 30) {
            return (String) cls.getMethod("getPath", new Class[0]).invoke(obj, new Object[0]);
        }
        File file = (File) cls.getMethod("getDirectory", new Class[0]).invoke(obj, new Object[0]);
        if (file != null) {
            return file.getPath();
        }
        return null;
    }

    @Nullable
    @RequiresApi(api = 19)
    public static String getFullPathFromTreeUri(@Nullable Uri uri, Context context) {
        String strH;
        String strH2 = null;
        if (uri == null) {
            return null;
        }
        if (Build.VERSION.SDK_INT < 30 && "com.android.providers.downloads.documents".equals(uri.getAuthority())) {
            String documentId = DocumentsContract.getDocumentId(uri);
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            if (documentId.equals("downloads")) {
                return path;
            }
            if (documentId.matches("^ms[df]\\:.*")) {
                return e.j(path, "/", c(context, uri));
            }
            if (documentId.startsWith("raw:")) {
                return documentId.split(":")[1];
            }
            return null;
        }
        String[] strArrSplit = DocumentsContract.getTreeDocumentId(uri).split(":");
        String str = strArrSplit.length > 0 ? strArrSplit[0] : null;
        try {
            StorageManager storageManager = (StorageManager) context.getSystemService("storage");
            Class<?> cls = Class.forName("android.os.storage.StorageVolume");
            Method method = storageManager.getClass().getMethod("getVolumeList", new Class[0]);
            Method method2 = cls.getMethod("getUuid", new Class[0]);
            Method method3 = cls.getMethod("isPrimary", new Class[0]);
            Object objInvoke = method.invoke(storageManager, new Object[0]);
            if (objInvoke != null) {
                int length = Array.getLength(objInvoke);
                int i10 = 0;
                while (true) {
                    if (i10 >= length) {
                        break;
                    }
                    Object obj = Array.get(objInvoke, i10);
                    String str2 = (String) method2.invoke(obj, new Object[0]);
                    if (((Boolean) method3.invoke(obj, new Object[0])) != null && "primary".equals(str)) {
                        strH2 = getDirectoryPath(cls, obj);
                        break;
                    }
                    if (str2 != null && str2.equals(str)) {
                        strH2 = getDirectoryPath(cls, obj);
                        break;
                    }
                    i10++;
                }
            }
        } catch (Exception unused) {
        }
        if (strH2 == null) {
            return File.separator;
        }
        String str3 = File.separator;
        if (strH2.endsWith(str3)) {
            strH2 = u1.h(strH2, 1, 0);
        }
        String[] strArrSplit2 = DocumentsContract.getTreeDocumentId(uri).split(":");
        if (strArrSplit2.length < 2 || (strH = strArrSplit2[1]) == null) {
            strH = str3;
        }
        if (strH.endsWith(str3)) {
            strH = u1.h(strH, 1, 0);
        }
        return strH.length() > 0 ? strH.startsWith(str3) ? u1.j(strH2, strH) : e.j(strH2, str3, strH) : strH2;
    }
}
