package com.secspace.lib.common.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("NullArgumentToVariableArgMethod")
@SuppressLint("NewApi")
public class SdUtil {
    private static final String TAG = "SdUtil";
    private SdUtil() {
    }

    public static List<String> getExtSDCardPaths() {
        List<String> paths = new ArrayList<String>();
        String extFileStatus = Environment.getExternalStorageState();
        File extFile = Environment.getExternalStorageDirectory();
        if (extFileStatus.equals(Environment.MEDIA_MOUNTED) && extFile.exists() && extFile.isDirectory()
                && extFile.canWrite()) {
            paths.add(extFile.getAbsolutePath());
        }
        try {
            // obtain executed result of command line code of 'mount', to judge
            // whether tfCard exists by the result
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("mount");
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            int mountPathIndex = 1;
            while ((line = br.readLine()) != null) {
                // format of sdcard file system: vfat/fuse
                if ((!line.contains("fat") && !line.contains("fuse") && !line.contains("storage"))
                        || line.contains("secure") || line.contains("asec") || line.contains("firmware")
                        || line.contains("shell") || line.contains("obb") || line.contains("legacy")
                        || line.contains("data")) {
                    continue;
                }
                String[] parts = line.split(" ");
                int length = parts.length;
                if (mountPathIndex >= length) {
                    continue;
                }
                String mountPath = parts[mountPathIndex];
                if (!mountPath.contains("/") || mountPath.contains("data") || mountPath.contains("Data")) {
                    continue;
                }
                File mountRoot = new File(mountPath);
                if (!mountRoot.exists() || !mountRoot.isDirectory() || !mountRoot.canWrite()) {
                    continue;
                }
                boolean equalsToPrimarySD = mountPath.equals(extFile.getAbsolutePath());
                if (equalsToPrimarySD) {
                    continue;
                }
                paths.add(mountPath);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return paths;
    }

    /**
     * 获取内置存储的路径
     *
     * @param context
     * @return
     */
    public static String getPrimaryStoragePath(Context context) {
        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", new Class[0]);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, new Object[]{});
            // first element in paths[] is primary storage path
            return paths[0];
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 只适合获取sd卡，不适合获取otg-U盘，当未插sd卡时可以获取，插入sd卡后则utg为第三张
     *
     * @param context
     * @return
     */
    public static String getSecondaryStoragePath(Context context) {
        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", new Class[0]);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, new Object[]{});
            // second element in paths[] is secondary storage path
            Log.d(TAG, "getSecondaryStoragePath: "+paths[1]);
            return paths[1];
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 普通方法获取内置路径
     */
    public static String getPrimaryStorageCommon(Context context) {
        File externalFilesDir = context.getExternalFilesDir(null);
        return externalFilesDir.toString();
    }

    /**
     * 普通方法获取内置cache目录
     */
    public static String getPrimaryStorageCacheCommon(Context context) {
        File externalCacheDir = context.getExternalCacheDir();
        return externalCacheDir.toString();
    }

    /**
     * 获取所有的存储路径
     *
     * @param context
     * @return
     */
    public static String[] getAllStoragePath(Context context) {
        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", new Class[0]);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, new Object[]{});
            // second element in paths[] is secondary storage path
            return paths;
        } catch (Exception e) {
            Log.e("yzy", "getSecondaryStoragePath() failed", e);
        }
        return null;
    }

    public static String getStorageState(String path, Context context) {
        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumeStateMethod = StorageManager.class.getMethod("getVolumeState",
                    new Class[]{String.class});
            String state = (String) getVolumeStateMethod.invoke(sm, path);
            return state;
        } catch (Exception e) {
            Log.e("yzy", "getStorageState() failed", e);
        }
        return null;
    }

    /**
     * 顺序：内置存储-SD卡-USB，当有两个外置存储时，otg-u盘是第三位
     *
     * @param context
     * @return
     */
    private static final String APP_PATH = "/sdcard";// 内置存储

    public static String getOTGPath(Context context) {
        String[] allStoragePath = getAllStoragePath(context);
        for (String s : allStoragePath) {
        }
        switch (allStoragePath.length) {
            case 1:
                return APP_PATH;
            case 2:
                return allStoragePath[1];
            case 3:
                return allStoragePath[2];
        }
        return null;
    }


    public static boolean getExternalStorageState() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 检查是否挂载
     */
    public static boolean checkMounted(Context context, String mountPoint) {
        if (mountPoint == null) {
            return false;
        }
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {
            Method getVolumeState = storageManager.getClass().getMethod("getVolumeState", String.class);
            String state = (String) getVolumeState.invoke(storageManager, mountPoint);
            return Environment.MEDIA_MOUNTED.equals(state);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
