package com.datarecovery.master.utils.xfile;

import android.net.Uri;
import android.os.Build;
import android.os.storage.StorageVolume;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

public class StorageVolumeUtil {

    /**
     * 获取存储卷的根目录
     */
    public static File getDirectory(StorageVolume storageVolume) {
        File directory;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            directory = storageVolume.getDirectory();
        } else {
            try {
                Method getPathFile = StorageVolume.class.getMethod("getPathFile");
                directory = (File) getPathFile.invoke(storageVolume);
            } catch (NoSuchMethodException | IllegalAccessException |
                     InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
        return directory;
    }

    /**
     * 获取存储卷的根目录Uri
     */
    public static Uri getRootUri(StorageVolume storageVolume) {
        Uri rootUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            rootUri = storageVolume.createOpenDocumentTreeIntent().getParcelableExtra(
                    DocumentsContract.EXTRA_INITIAL_URI);
        } else {
            rootUri = DocumentsContract.buildRootUri("com.android.externalstorage.documents",
                    (storageVolume.isPrimary() ? "primary" : storageVolume.getUuid()));
        }
        return rootUri;
    }

    public static Uri getTreeUri(StorageVolume storageVolume) {
        return Uri.parse(getRootUri(storageVolume).toString().replace("/root/", "/tree/"));
    }

    public static String getMediaStoreVolumeName(StorageVolume storageVolume) {
        String volumeName;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            volumeName = storageVolume.getMediaStoreVolumeName();
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            volumeName = storageVolume.isPrimary() ? MediaStore.VOLUME_EXTERNAL_PRIMARY : getNormalizedUuid(storageVolume);
        } else {
            volumeName = storageVolume.isPrimary() ? "external" : getNormalizedUuid(storageVolume);
        }
        return volumeName;
    }

    public static String getNormalizedUuid(StorageVolume storageVolume) {
        String uuid = storageVolume.getUuid();
        return uuid == null ? null : uuid.toLowerCase(Locale.US);
    }
}