/**
 * 文件名：AddPictureUtil.java
 * 描述：网络连接状态
 * 包名：cn.com.kmlt.monstarBase.utils.net
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.utils.picture;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.mgq.base.utils.base.MiniApp;
import com.mgq.base.utils.file.FileUtil;
import com.mgq.base.utils.filepath.FilePath;
import com.mgq.base.utils.logger.Logger;


/**
 * 调用相机或者相册获得图片dialog
 * 
 * @author
 */
public class AddPictureUtil {

	/**
	 * TAG
	 */
	private static final String TAG = "AddPictureUtil";

	/**
	 * 新拍相片名称前缀
	 */
	private static final String PHOTO_STRING = "cachePhoto";

	private static final String IMAGE_UNSPECIFIED = "image/*";

	/**
	 * 图片类型
	 */
	private static final String IMAGE_TYPE = ".jpeg";

	/**
	 * 抓取的图片uri
	 */
	private Uri imageCaptureUri;

	/**
	 * 抓取的裁剪后的图片uri
	 */
	private Uri imageCaptureUriCutted;

	/**
	 * 调用的Activity
	 */
	private Activity activity = null;

	/**
	 * 启动系统相册或者相机获得图片的requestCode
	 */
	public interface GetPicture {
		/**
		 * 基础状态
		 */
		int BASE = 6000;

		/**
		 * 从相机获取照片requestCode
		 */
		int PICK_FROM_CAMERA = BASE + 1;

		/**
		 * 从相册获取图片requestCode
		 */
		int PICK_FROM_FILE = BASE + 2;

		/**
		 * 裁剪相片requestCode
		 */
		int PICK_CROP_IMAGE = BASE + 3;
	}

	/**
	 * 图像缓存SD卡路径的目录，主要用于缓存
	 */
	public static final String SAVE_SD_FLODER = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/imagecache";

	/**
	 * 构造方法
	 * 
	 * @param activity
	 *            参数Activity
	 */
	public AddPictureUtil(Activity activity) {
		this.activity = activity;
	}

	/**
	 * 取得选取或者拍照得到的原始图片的uri
	 * 
	 * @return 原始图片的uri
	 */
	public Uri getImageCaptureUri() {
		// 判断文件长度为0,则删除该文件,返回空
		File file = new File(filterPath(MiniApp.getContext(), imageCaptureUri));
		if (file != null && file.length() == 0) {
			Log.e(TAG, "getImageCaptureUri() - first check: file length is 0, wait file");
			int waitSecond = 0;
			do {
				try {
					Thread.sleep(2000);
					waitSecond += 2;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}while (waitSecond < 10 && file.length() == 0);

			if (file != null && file.length() == 0){
				Log.e(TAG, "getImageCaptureUri() : file length is 0, delete file, return null");
				if (!file.delete()) {
					Logger.e(TAG, "file delete fail");
				}
				return null;
			}
		}
		return imageCaptureUri;
	}

	/**
	 * 取得裁剪后的图片的uri
	 * 
	 * @return 裁剪后的图片的uri
	 */
	public Uri getImageCaptureUriCutted() {
		// 判断文件长度为0,则删除该文件,返回空
		File file = new File(filterPath(MiniApp.getContext(), imageCaptureUriCutted));
		if (file != null && file.length() == 0) {
			Log.e(TAG, "getImageCaptureUriCutted() - first check: file length is 0, wait file");
			int waitSecond = 0;
			do {
				try {
					Thread.sleep(1000);
					waitSecond += 1;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}while (waitSecond < 10 && file.length() == 0);

			if (file != null && file.length() == 0){
				Log.e(TAG, "getImageCaptureUriCutted() - second check: file length is 0, delete file, return null");
				if (!file.delete()) {
					Logger.e(TAG, "file delete fail");
				}
				return null;
			}
		}
		return imageCaptureUriCutted;
	}

	/**
	 * 启动从相册获取图片
	 */
	public void getPicFromAlbums() {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				IMAGE_UNSPECIFIED);

		activity.startActivityForResult(intent, GetPicture.PICK_FROM_FILE);
	}

	private static boolean isExistSdcard() {
		if (!isEmulator()) {
			return Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED);
		}
		return true;
	}

	private static boolean isEmulator() {
		return android.os.Build.MODEL.equals("sdk");
	}

	public static File getFileByPath(String filePath) {
		filePath = filePath.replaceAll("\\\\", "/");
		boolean isSdcard = false;
		int subIndex = 0;
		if (filePath.indexOf("/sdcard") == 0) {
			isSdcard = true;
			subIndex = 7;
		} else if (filePath.indexOf("/mnt/sdcard") == 0) {
			isSdcard = true;
			subIndex = 11;
		}

		if (isSdcard) {
			if (isExistSdcard()) {
				File sdCardDir = Environment.getExternalStorageDirectory();// 获取SDCard目录,2.2的时候为:/mnt/sdcard
																			// 2.1的时候为：/sdcard，所以使用静态方法得到路径会好一点。
				String fileName = filePath.substring(subIndex);
				return new File(sdCardDir, fileName);
			} else if (isEmulator()) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				String fileName = filePath.substring(subIndex);
				return new File(sdCardDir, fileName);
			}
			return null;
		} else {
			return new File(filePath);
		}
	}

	/**
	 * 通过提供的文件名在默认路径下生成文件
	 * 
	 * @param fileName
	 *            文件的名称
	 * @return 生成的文件
	 * @throws IOException
	 */
	public static File createFile(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			Logger.e(TAG, "in method createFile, filePath is null");

			return null;
		}

		String folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
		File folder = getFileByPath(folderPath);
		folder.mkdirs();
		File file = getFileByPath(filePath);

		if (file.exists()) {
			file.delete();
		}

		try {
			file.createNewFile();
		} catch (Exception e) {
			Logger.e(TAG, "create file fail, filePath = " + filePath);
		}

		return file;
	}

	/**
	 * 启动从相机获取图片
	 */
	public void getPicFromCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String imagePath = SAVE_SD_FLODER + File.separator
				+ PHOTO_STRING
				+ String.valueOf(System.currentTimeMillis()) + IMAGE_TYPE;
		File file = createFile(imagePath);
		if (file == null) {
			return;
		} else {
			imageCaptureUri = Uri.fromFile(file);
		}

		// 设置抓取照片存储路径
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				imageCaptureUri);
		try {
			// 设置不返回图像信息,因为已经存储在了对应文件中
			intent.putExtra("return-data", false);
			// 调用系统相机
			activity.startActivityForResult(intent, GetPicture.PICK_FROM_CAMERA);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}

	public String createImageFilePath(Context context){
		String imageFolder = SAVE_SD_FLODER;
		String cacheFolder = FilePath.getExternalDiskCacheDir(context);
		if ( cacheFolder != null && !cacheFolder.isEmpty()){
			imageFolder = cacheFolder;
		}
		String imagePath = imageFolder + File.separator
				+ PHOTO_STRING
				+ String.valueOf(System.currentTimeMillis()) + IMAGE_TYPE;
		return imagePath;
	}

	public void getZippedPicFromCamera(){
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		try {
			// 调用系统相机
			activity.startActivityForResult(intent, GetPicture.PICK_FROM_CAMERA);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void startPhotoZoom(Context context, Uri uri, int size) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		String imageFolder = SAVE_SD_FLODER;
		String cacheFolder = FilePath.getExternalDiskCacheDir(context);
		if ( cacheFolder != null && !cacheFolder.isEmpty()){
			imageFolder = cacheFolder;
		}
		String imagePath = imageFolder + File.separator
				+ PHOTO_STRING
				+ String.valueOf(System.currentTimeMillis()) + IMAGE_TYPE;
		File file = FileUtil.createFile(imagePath, false);
		if (file == null) {
			return;
		} else {
			imageCaptureUriCutted = Uri.fromFile(file);
		}
		// 设置抓取照片存储路径
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				imageCaptureUriCutted);
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");

		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("scale", true);//黑边
        intent.putExtra("scaleUpIfNeeded", true);//黑边
		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", size);
		intent.putExtra("outputY", size);

		intent.putExtra("return-data", false);

		activity.startActivityForResult(intent, GetPicture.PICK_CROP_IMAGE);
	}

	/**
	 * 获得多媒体的地址
	 * 
	 * @param context
	 *            上下文
	 * @param uri
	 *            多媒体URI
	 * @return String 图片地址
	 */
	public static String filterPath(Context context, Uri uri) {
		if (uri == null) {
			return null;
		}

		String path = null;
		if (uri.getScheme().equals("file")) {
			path = uri.getPath();
		} else {
			path = getPathFromUri(context, uri);
		}

		return path;
	}

	/**
	 * 从uri获取图片路径
	 * 
	 * @param context
	 *            上下文环境
	 * @param uri
	 *            图片的uri
	 * @return 图片路径
	 */
	public static String getPathFromUri(Context context, Uri uri) {
		if (uri == null) {
			return null;
		}
		ContentResolver cr = context.getContentResolver();

		// 查询数据库
		Cursor cursor = cr
				.query(uri, new String[] { MediaStore.Images.Media.DATA },
						null, null, null);
		String path = null;
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				// 获取数据库中的文件路径
				path = cursor.getString(cursor
						.getColumnIndex(MediaStore.Images.Media.DATA));
			}
			cursor.close();
		}
		return path;
	}

	public static Bitmap getBitmapByWidth(String localImagePath, int width) {
		if (TextUtils.isEmpty(localImagePath)) {
			return null;
		}

		Bitmap temBitmap = null;

		try {
			BitmapFactory.Options outOptions = new BitmapFactory.Options();

			// 设置该属性为true，不加载图片到内存，只返回图片的宽高到options中。
			outOptions.inJustDecodeBounds = true;

			// 加载获取图片的宽高
			BitmapFactory.decodeFile(localImagePath, outOptions);

			int height = outOptions.outHeight;
			if (outOptions.outWidth > width) {
				// 根据宽设置缩放比例
				outOptions.inSampleSize = outOptions.outWidth / width;
				outOptions.outWidth = width;

				// 计算缩放后的高度
				height = outOptions.outHeight / outOptions.inSampleSize;
				outOptions.outHeight = height;
			}

			Log.i("evening", outOptions.inSampleSize + "====="
					+ outOptions.outWidth + "====" + width + "====="
					+ localImagePath);
			// 重新设置该属性为false，加载图片返回
			outOptions.inJustDecodeBounds = false;
			outOptions.inPurgeable = true;
			outOptions.inInputShareable = true;
			temBitmap = BitmapFactory.decodeFile(localImagePath, outOptions);
		} catch (Throwable t) {
			t.printStackTrace();
		}

		return temBitmap;
	}
}
