package com.base.utils.ui.image.crop;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import com.base.utils.R;
import com.base.utils.tools.android.IntentUtil;
import com.base.utils.tools.java.FileUtil;

import java.io.File;

/**
 * 对裁剪封装
 * 1.从相册选择图片  -->然后裁剪
 * 2.从相机拍摄图片  -->然后裁剪
 * <p>
 * 3.可单独使用 从相册选择图片的功能
 * 4.可单独使用 从相机拍摄图片的功能
 *
 * @author yuyife
 * create by 2017-08-11
 */

public class CropUtil {
    private static final String selectImageName = "crop_util_select_image";             //从相机、相册选择后的某图片，保存在根目录的名字

    private static boolean isCrop = true;          //默认是对照片进行裁剪
    private static String currentSelectName = "x"; //本次选择照片的命名


    /**
     * 获取上次选择的图片
     *
     * @return file 上次保存的图片
     */
    public static File getLastImage() {
        return getImageByName(currentSelectName);
    }

    /**
     * 获取指定name的图片
     *
     * @return file 图片
     */
    public static File getImageByName(String name) {
        return new File(FileUtil.getAppFileDir() + File.separator + selectImageName + name + FileUtil.FILE_PNG);
    }

    /**
     * 开始(选择来源)
     * 务必和 public static void handleCrop()一起使用
     */
    public static void start(final Activity activity, boolean isCrop, String selectImageName) {
        CropUtil.isCrop = isCrop;
        CropUtil.currentSelectName = selectImageName;
        new android.support.v7.app.AlertDialog.Builder(activity)
                .setTitle(activity.getString(R.string.label_crop_source))
                .setItems(new String[]{activity.getString(R.string.value_photo), activity.getString(R.string.value_camera)},
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                switch (i) {
                                    case 0:
                                        startPhoto(activity);
                                        break;
                                    case 1:
                                        startCamera(activity);
                                        break;
                                }
                            }
                        })
                .setPositiveButton(R.string.resource_public_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    /**
     * 从相册选择
     * 单独调用的时候，
     * 务必和 public static void handlePhoto()一起使用
     */
    public static void startPhoto(Activity activity) {
        IntentUtil.imageSelect(activity, CropConstant.IMAGE_SELECT_PHOTO_CODE);
    }

    /**
     * 从相机拍摄
     * 单独调用的时候，
     * 务必和 public static void handleCamera()一起使用
     */
    public static void startCamera(Activity activity) {
        IntentUtil.cameraArtwork(activity, FileUtil.getAppFileDir(), selectImageName + currentSelectName, CropConstant.IMAGE_SELECT_CAMERA_ARTWORK_CODE);
    }

    public interface OnHandleCallback {
        void onProgressStart();     //可以弹出提示

        void onProgressEnd();       //可以关闭提示

        void callback(File file);   //返回文件
    }

    private static Uri defaultUri = null;//从相机、相机选择图片后，请务必经历：Uri--File-Uri，图片裁剪后，会直接操作defaultUri并返回

    /**
     * 处理裁剪
     * 在Activity的 onActivityResult()中触发
     */
    public static void handleCrop(final Activity activity,
                                  final int requestCode,
                                  final int resultCode,
                                  final Intent data,
                                  final OnHandleCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (resultCode == Activity.RESULT_OK) {
                    switch (requestCode) {
                        case CropConstant.IMAGE_SELECT_CROP_CODE:
                            //得到裁剪后的图片
                            final String fileCrop = FileUtil.getPathByUri4kitkat(activity, defaultUri);
                            File file = null;
                            if (fileCrop != null) {
                                file = new File(fileCrop);
                            }
                            postCallbackUiThread(activity, callback, file);

                            break;
                        case CropConstant.IMAGE_SELECT_PHOTO_CODE:
                            //来自相册
                            handlePhoto(CropUtil.isCrop, activity, data, callback);
                            break;
                        case CropConstant.IMAGE_SELECT_CAMERA_ARTWORK_CODE:
                            //来自相机
                            handleCamera(CropUtil.isCrop, activity, callback);
                            break;
                    }
                } else {
                    postCallbackUiThread(activity, callback, null);
                }
            }
        }).start();

    }

    /**
     * 处理从相册选择的图片
     * 真正的执行者
     * 在Activity的 onActivityResult()中触发
     */
    private static void handlePhoto(boolean isCrop, final Activity activity, final Intent data, final OnHandleCallback callback) {
        postProgressStartUiThread(activity, callback);
        Uri photoUri = data.getData();
        String photoPath = FileUtil.getPathByUri4kitkat(activity, photoUri);
        if (photoPath != null) {
            final File filePhoto = new File(photoPath);
            Bitmap bitmap = BitmapFactory.decodeFile(filePhoto.getPath());
            FileUtil.saveBitmapToAppDir(Bitmap.CompressFormat.PNG, bitmap, selectImageName + currentSelectName);
            defaultUri = Uri.fromFile(new File(FileUtil.getAppFileDir() + File.separator + selectImageName + currentSelectName + FileUtil.FILE_PNG));
            if (isCrop) {
                IntentUtil.imageCrop(activity,
                        defaultUri,
                        CropConstant.IMAGE_SELECT_CROP_CODE);
            } else {
                postCallbackUiThread(activity, callback, new File(FileUtil.getAppFileDir() + File.separator + selectImageName + currentSelectName + FileUtil.FILE_PNG));
            }
        } else {
            postCallbackUiThread(activity, callback, null);

        }
    }

    /**
     * 处理从相册选择的图片
     * 在Activity的 onActivityResult()中触发
     */
    public static void handlePhoto(final Activity activity,
                                   final int requestCode,
                                   final int resultCode,
                                   final Intent data,
                                   final OnHandleCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (resultCode == Activity.RESULT_OK) {
                    switch (requestCode) {
                        case CropConstant.IMAGE_SELECT_PHOTO_CODE:
                            //来自相册
                            handlePhoto(false, activity, data, callback);
                            break;
                    }
                } else {
                    postCallbackUiThread(activity, callback, null);
                }
            }
        }).start();

    }


    /**
     * 处理从相机拍摄的图片
     * 真正的执行者
     */
    private static void handleCamera(boolean isCrop, final Activity activity, final OnHandleCallback callback) {
        //来自相机
        postProgressStartUiThread(activity, callback);
        final File fileCamera = new File(FileUtil.getAppFileDir() + File.separator + selectImageName + currentSelectName + FileUtil.FILE_PNG);
        defaultUri = Uri.fromFile(fileCamera);
        if (isCrop) {
            IntentUtil.imageCrop(activity,
                    defaultUri,
                    CropConstant.IMAGE_SELECT_CROP_CODE);
        } else {
            postCallbackUiThread(activity, callback, fileCamera);
        }

    }

    /**
     * 处理从相机拍摄的图片
     * 在Activity的 onActivityResult()中触发
     */
    public static void handleCamera(final Activity activity,
                                    final int requestCode,
                                    final int resultCode,
                                    final Intent data,
                                    final OnHandleCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (resultCode == Activity.RESULT_OK) {
                    switch (requestCode) {
                        case CropConstant.IMAGE_SELECT_CAMERA_ARTWORK_CODE:
                            //来自相机
                            handleCamera(false, activity, callback);
                            break;
                    }
                } else {
                    postCallbackUiThread(activity, callback, null);
                }
            }
        }).start();

    }

    private static void postCallbackUiThread(Activity activity, final OnHandleCallback callback, final File file) {
        postProgressEndUiThread(activity,callback);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.callback(file);
                }
            }
        });
    }

    private static void postProgressStartUiThread(Activity activity, final OnHandleCallback callback) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onProgressStart();
                }
            }
        });
    }

    private static void postProgressEndUiThread(Activity activity, final OnHandleCallback callback) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onProgressEnd();
                }
            }
        });
    }

}
