package cn.net.caoyao.cpzshandset.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import android.os.Environment;
import android.text.TextUtils;

public class GetSdcardPath {
	
	//private static String [] FilterKEY = {"emulated","knox-emulated","privatemode","legacy"};
	private static String  FilterKEYString = "emulated,knox-emulated,privatemode,legacy";
	/**
	 * 获取外置默认SD卡路径
	 * 
	 * @return
	 */
	public static String getSDCardPath() {
		String cmd = "cat /proc/mounts";
		Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
		String result = null;
		try {
			Process p = run.exec(cmd);// 启动另一个进程来执行命令
			BufferedInputStream in = new BufferedInputStream(p.getInputStream());
			BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

			String lineStr;
			while ((lineStr = inBr.readLine()) != null) {
				// 获得命令执行后在控制台的输出信息
				// LOG.i("CommonUtil:getSDCardPath", lineStr);
				if (lineStr.contains("sdcard")
						&& lineStr.contains(".android_secure")) {
					String[] strArray = lineStr.split(" ");
					if (strArray != null && strArray.length >= 5) {
						result = strArray[1].replace("/.android_secure", "");
						return result;
					}
				}
				// 检查命令是否执行失败。
				if (p.waitFor() != 0 && p.exitValue() == 1) {
					// p.exitValue()==0表示正常结束，1：非正常结束
					// LOG.e("CommonUtil:getSDCardPath", "命令执行失败!");
				}
			}
			inBr.close();
			in.close();
		} catch (Exception e) {
			// LOG.e("CommonUtil:getSDCardPath", e.toString());

			return Environment.getExternalStorageDirectory().getPath();
		}
		if (TextUtils.isEmpty(result)) {
			result = Environment.getExternalStorageDirectory().getPath();
		}
		return result;
	}

	/**
	 * 获取外置SD卡路径List
	 * 
	 * @return
	 */
	public static Map<String, String> getSDList() {
		Map<String, String> respone = new HashMap<String, String>();
		String cmd = "cat /proc/mounts";
		Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
		try {
			Process p = run.exec(cmd);// 启动另一个进程来执行命令
			BufferedInputStream in = new BufferedInputStream(p.getInputStream());
			BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

			String lineStr;
			while ((lineStr = inBr.readLine()) != null) {
				// 获得命令执行后在控制台的输出信息
				// LOG.i("CommonUtil:getSDCardPath", lineStr);
				if (lineStr.contains("sdcard")
						&& !lineStr.contains(".android_secure")) {
					String[] strArray = lineStr.split(" ");
					if (strArray != null && strArray.length >= 5) {
						String value = strArray[1];
						String key = value
								.substring(value.lastIndexOf("/") + 1);
						if (!respone.containsKey(key)) {
							if(!FilterKEYString.contains(key))
							{
								if(key.equals("0")&& value.contains("storage"))
								{
									key = "sdcard" + key;
								}
								
								respone.put(key, value);
								
							}
						}
					}
				}
				// 检查命令是否执行失败。
				if (p.waitFor() != 0 && p.exitValue() == 1) {
					// p.exitValue()==0表示正常结束，1：非正常结束
					// LOG.e("CommonUtil:getSDCardPath", "命令执行失败!");
				}
			}
			inBr.close();
			in.close();
		} catch (Exception e) {
			// LOG.e("CommonUtil:getSDCardPath", e.toString());
			respone = null;
		}

		return respone;
	}
	
	 /** 
     * 获取扩展存储路径，TF卡、U盘 
     */  
    public static Map<String, String> getExternalStorageDirectory(){
    	
    	Map<String, String> respone = new HashMap<String, String>();
        String dir = new String();  
        try {  
            Runtime runtime = Runtime.getRuntime();  
            Process proc = runtime.exec("mount");  
            InputStream is = proc.getInputStream();  
            InputStreamReader isr = new InputStreamReader(is);  
            String line;  
            BufferedReader br = new BufferedReader(isr);  
            while ((line = br.readLine()) != null) {  
                if (line.contains("secure")) continue;  
                if (line.contains("asec")) continue;  
                  
                if (line.contains("fat")) {  
                    String columns[] = line.split(" ");  
                    if (columns != null && columns.length > 1) {  
                        //dir = dir.concat(columns[1] + "\n");
                    	respone=getMap(respone, columns[1]);
                    }  
                } else if (line.contains("fuse")) {  
                    String columns[] = line.split(" ");  
                    if (columns != null && columns.length > 1) {  
                        //dir = dir.concat(columns[1] + "\n");
                    	respone=getMap(respone, columns[1]);
                    }  
                }  
            }  
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        //return dir;  
        return respone;
    } 
    
    public static Map<String, String> getMap(Map<String, String> respone,String path) {
		
    	if (!TextUtils.isEmpty(path)) {
    		int index=path.lastIndexOf("/");
    		if (index!=-1) {
    			respone.put(path.substring(index+1), path);
			}
			
		}
    	return respone;
    	
	}
    
	
}
