/**
 * 文件名：ImageUtil.java
 * 描述：ImageUtil工具类
 * 包名：cn.com.kmlt.monstarBase.utils.image
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.utils.image;

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.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.mgq.base.utils.file.FileUtil;
import com.mgq.base.utils.logger.Logger;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ImageUtil {
    private static final String TAG = "ImageUtil";
   
    /*用来标识请求照相功能的activity*/  
    public static final int CAMERA_WITH_DATA = 3023;  
  
    /*用来标识请求gallery的activity*/  
    public static final int PHOTO_PICKED_WITH_DATA = 3021;  
  
    /*拍照的照片存储位置*/  
    public static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");  
  
      
    public static Intent getTakePickIntent(File f) {  
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);  
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));  
        return intent;  
    }  
      
    /** 
    * 用当前时间给取得的图片命名 
    *  
    */  
    public static String getPhotoFileName() {  
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyy-MM-dd_HH_mm_ss");
        return dateFormat.format(date) + ".jpg";  
    }  
      
    // 封装请求Gallery的intent  
    public static Intent getPhotoPickIntent() {  
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);  
        intent.setType("image/*");  
//        intent.putExtra("crop", "true");  
//        intent.putExtra("aspectX", 1);  
//        intent.putExtra("aspectY", 1);  
//        intent.putExtra("outputX", 80);  
//        intent.putExtra("outputY", 80);  
//        intent.putExtra("return-data", true);  
        return intent;  
    }  
      
    /**  
    * Constructs an intent for image cropping. 调用图片剪辑程序  
    */  
    public static Intent getCropImageIntent(Uri photoUri) {  
        Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(photoUri, "image/*");  
        intent.putExtra("crop", "true");  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        intent.putExtra("outputX", 80);  
        intent.putExtra("outputY", 80);  
        intent.putExtra("return-data", true);  
        return intent;  
    }  
    
    /**
     * 根据指定的宽和高读取一个Bitmap
     *
     * @param path
     * @param width
     * @param height
     * @return
     */
    public static Bitmap readBitmap(String path, int width, int height) {
        int srcWidth = readWidth(path);
        int srcHeight = readHeight(path);
        Options options = new Options();
        options.inSampleSize = getSampleSize(srcWidth, srcHeight, width, height);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(fis, null, options);
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bitmap != null) {
            return Bitmap.createScaledBitmap(bitmap, width, height, false);
        }
        return null;
    }
    private static int getSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
        float xRatio = (float) dstWidth / srcWidth;
        float yRatio = (float) dstHeight / srcHeight;
        int size = 1;
        if (xRatio > yRatio) {
            int i = 1;
            while (((float) srcWidth / i) >= dstWidth) {
                i *= 2;
            }
            size = i / 2;
        } else {
            int i = 1;
            while (((float) srcHeight / i) >= dstHeight) {
                i *= 2;
            }
            size = i / 2;
        }
        return size;
    }
    /**
     * 读取图片的宽度
     * 
     * @param context
     * @param resId
     * @return
     */
    public static int readWidth(Context context, int resId) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, options);
        return options.outWidth;
    }

    /**
     * 读取图片的高度
     * 
     * @param context
     * @param resId
     * @return
     */
    public static int readHeight(Context context, int resId) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, options);
        return options.outHeight;
    }

    /**
     * 读取图片的宽度
     * 
     * @param path
     * @return
     */
    public static int readWidth(String path) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BitmapFactory.decodeStream(fis, null, options);
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return options.outWidth;
    }

    /**
     * 读取图片的高度
     * 
     * @param path
     * @return
     */
    public static int readHeight(String path) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BitmapFactory.decodeStream(fis, null, options);
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return options.outHeight;
    }
    /**
     * Drawable对象转化Bitmap对象
     * 
     * @param drawable Drawable对象
     * @return Bitmap对象
     */
    public static Bitmap drawableToBitmap(Drawable drawable)
    {

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        // canvas.setBitmap(bitmap);
        drawable.setBounds(0,
                0,
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * Bitmap对象转化byte数组
     * 
     * @param bitmap Bitmap对象
     * @return byte数组
     */
    public static byte[] bitmapToBytes(Bitmap bitmap)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Byte数组转化为Bitmap对象
     * 
     * @param data byte数组
     * @return Bitmap对象
     */
    public static Bitmap bytesToBimap(byte[] data)
    {
        if (data.length != 0)
        {
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        else
        {
            return null;
        }
    }

    public static Bitmap createBlurBitmap(Bitmap src){
        Bitmap dstBitmap = null;

        int scaleRatio = 1;
        int blurRadius = 30;

        if (src != null){
            int scaledWidth = src.getWidth() / scaleRatio;
            int scaledHeight = src.getHeight() / scaleRatio;
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(src,
                    scaledWidth, scaledHeight, false);
            Bitmap blurBitmap = FastBlurUtil.doBlur(scaledBitmap, blurRadius, true);
            dstBitmap = blurBitmap;
        }
        return dstBitmap;
    }

    public static boolean saveImage(Bitmap photo, String spath) {
        try {
            File file = FileUtil.createFile(spath, false);
            if (file == null)
                return false;

            FileOutputStream outputStream = new FileOutputStream(spath, false);
            if (outputStream != null){
                BufferedOutputStream bos = new BufferedOutputStream(outputStream);
                photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * auto fix the imageOrientation
     * @param bm source
     * @param path image path if null use uri
     */
    public static Bitmap autoFixOrientation(Bitmap bm, String path) {
        int deg = 0;
        try {
            ExifInterface exif = new ExifInterface(path);
            if (exif == null) {
                Log.e(TAG,"exif is null check your uri or path");
                return bm;
            }

            String rotate = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
            int rotateValue = Integer.parseInt(rotate);
            Log.d(TAG, "orientetion : " + rotateValue);
            switch (rotateValue) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    deg = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    deg = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    deg = 270;
                    break;
                default:
                    deg = 0;
                    break;
            }
        } catch (Exception ee) {
            Log.d("catch img error", "return");
            return bm;
        }
        Matrix m = new Matrix();
        m.preRotate(deg);
        bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
        return bm;
    }

    /**
     * 取得裁剪后的图片的uri
     *
     * @return 裁剪后的图片的uri
     */
    public static boolean isImageCaptureCutted(File file) {
        boolean isCutted = false;
        if (file != null && file.length() > 0){
            return true;
        }
        // 判断文件长度为0,则删除该文件,返回空
        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 false;
            }
            isCutted = true;
        }
        return isCutted;
    }

    /**
     * 获得多媒体的地址
     *
     * @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;
    }
}
