/**
 * 文件名：FilePath.java
 * 描述：文件工具类
 * 包名：cn.com.kmlt.monstarBase.utils.file(可根据包名,操作应用下"具体文件夹/文件")
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.utils.filepath;


import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;

import java.io.File;

public class FilePath {

	
	static String packageName = "vkeshare";
	
	public static void setPackageName(String strName)
	{
		packageName = strName;
	}

	public static String getRealFilePath(final Context context, final Uri uri ) {
		if ( null == uri ) return null;
		final String scheme = uri.getScheme();
		String data = null;
		if ( scheme == null )
			data = uri.getPath();
		else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
			data = uri.getPath();
		} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
			Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
			if ( null != cursor ) {
				if ( cursor.moveToFirst() ) {
					int index = cursor.getColumnIndex( ImageColumns.DATA );
					if ( index > -1 ) {
						data = cursor.getString( index );
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	public static String getImageAbsolutePath(Context context, Uri imageUri) {
		if (context == null || imageUri == null)
			return null;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
			if (isExternalStorageDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			} else if (isDownloadsDocument(imageUri)) {
				String id = DocumentsContract.getDocumentId(imageUri);
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[]{split[1]};
				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		} // MediaStore (and general)
		else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(imageUri))
				return imageUri.getLastPathSegment();
			return getDataColumn(context, imageUri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			return imageUri.getPath();
		}
		return null;
	}

	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = {column};
		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	 public static boolean isExternalStorageDocument(Uri uri) {
		 return "com.android.externalstorage.documents".equals(uri.getAuthority());
	 }

	 /**
	  * @param uri The Uri to check.
	  * @return Whether the Uri authority is DownloadsProvider.
	  */
	  public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	  }

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	 public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	public static Uri getUriFromPath(Context context, Uri uri){
		Uri formatUri = uri;
		if (uri.getScheme().equals("file") ) {
			String path = uri.getEncodedPath();
			if (path != null && !path.isEmpty()) {
				path = Uri.decode(path);
				ContentResolver cr = context.getContentResolver();
				Cursor cursor = cr.query(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						new String[] { ImageColumns._ID },
						MediaStore.Images.Media.DATA + "=? ",
						new String[] { path },
						null);
				if (cursor != null && cursor.moveToFirst()) {
					int id = cursor.getInt(cursor
							.getColumnIndex(MediaStore.MediaColumns._ID));
					Uri baseUri = Uri.parse("content://media/external/images/media");
					return Uri.withAppendedPath(baseUri, "" + id);
				} else {
					File imageFile = new File(path);
					if (imageFile.exists()) {
						ContentValues values = new ContentValues();
						values.put(MediaStore.Images.Media.DATA, path);
						return context.getContentResolver().insert(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
					} else {
						return null;
					}
				}
			}
		}
		return formatUri;
	}

	public static String getDiskCacheDir(Context context){
		String cachePath = context.getCacheDir().getAbsolutePath();
		return cachePath;
	}

	public static String getDiskFileDir(Context context){
		String filePath = context.getFilesDir().getAbsolutePath();
		return filePath;
	}

	public static String getExternalDiskCacheDir(Context context){
		String cachePath = null;
		File fileCacheDir = null;
		if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				|| !Environment.isExternalStorageRemovable() ){
			fileCacheDir = context.getExternalCacheDir();
		}
		if (fileCacheDir == null){
			fileCacheDir = context.getCacheDir();
		}
		if (fileCacheDir != null) {
			cachePath = fileCacheDir.getAbsolutePath();
		}
		return cachePath;
	}

}
