package com.datarecovery.master.utils.xfile;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class XStorageManager {

    /**
     * 获取所有可读的存储卷
     */
    public static List<StorageVolume> getReadableStorageVolumes(Context context) {
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        List<StorageVolume> storageVolumes = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            storageVolumes = storageManager.getStorageVolumes();
        } else {
            try {
                Method getVolumeList = StorageManager.class.getMethod("getVolumeList");
                StorageVolume[] storageVolumes21 = (StorageVolume[]) getVolumeList.invoke(storageManager);
                storageVolumes = Arrays.asList(storageVolumes21);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (storageVolumes == null) {
            storageVolumes = new ArrayList<>();
        }
        ArrayList<StorageVolume> result = new ArrayList<>(storageVolumes.size());
        for (StorageVolume storageVolume : storageVolumes) {
            if (isReadable(storageManager, storageVolume)) {
                result.add(storageVolume);
            }
        }
        return result;
    }

    private static boolean isReadable(StorageManager storageManager, StorageVolume storageVolume) {
        if (storageVolume == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Objects.equals(storageVolume.getState(), Environment.MEDIA_MOUNTED)
                    || Objects.equals(storageVolume.getState(), Environment.MEDIA_MOUNTED_READ_ONLY);
        } else {
            try {
                Method getPath = StorageVolume.class.getMethod("getPath");
                String path = (String) getPath.invoke(storageVolume);
                Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class);
                String state = (String) getVolumeState.invoke(storageManager, path);
                return Objects.equals(state, Environment.MEDIA_MOUNTED)
                        || Objects.equals(state, Environment.MEDIA_MOUNTED_READ_ONLY);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    }
}
