package me.nereo.multi_image_selector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

import java.io.File;

import me.nereo.multi_image_selector.view.ClipImageBorderView;
import me.nereo.multi_image_selector.view.zoomable.DefaultZoomableController;
import me.nereo.multi_image_selector.view.zoomable.ZoomableDraweeView;

/**
 * Created by sunny on 2015/12/22.
 * 图片裁剪
 */
public class ClipPhotoActivity extends Activity implements OnClickListener, IBitmapShow {
    public static final String TAG = ClipPhotoActivity.class.getSimpleName();

    private String imgUrl;

    private TextView mTitle;
    private Button mCommit;
    private ImageView mBack;
    private ZoomableDraweeView mGestureImageView;
    private ClipImageBorderView clip_image_borderview;

    //图片的平移与缩放
    float mCurrentScale;
    float last_x = -1;
    float last_y = -1;
    boolean move = false;

    public static void startClipPhotoActivity(Context context, String uri) {
        Intent targetIntent = new Intent(context, ClipPhotoActivity.class);
        targetIntent.putExtra(TAG, uri);
        context.startActivity(targetIntent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clip_photo);
        setTitle("图片裁剪");

        initIntentParams();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
      /*  new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                getBitmap();
            }
        },100);*/

        getBitmap();

    }

    private void getBitmap() {

        int width = clip_image_borderview.getWidth();
        int height = clip_image_borderview.getHeight();
        Log.e("with", "with===" + width + "\nheight===" + height);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int screenWidth = displayMetrics.widthPixels;
        int screenHeight = displayMetrics.heightPixels;
               /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(screenWidth - 40, screenWidth - 40);
                layoutParams.gravity = Gravity.CENTER;
                mGestureImageView.setLayoutParams(layoutParams);*/
        if (!TextUtils.isEmpty(imgUrl)) {

            //  ImageLoaderUtils.load(imgUrl,mGestureImageView);

            //解决图片倒置
            ImageRequest imageRequest = ImageRequestBuilder
                    .newBuilderWithSource(Uri.parse("file://" + imgUrl))
                    .setAutoRotateEnabled(true).build();

            //解决图片多指缩放
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setImageRequest(imageRequest)
                    .setTapToRetryEnabled(true)
                    .build();

          /*  DefaultZoomableController controller = DefaultZoomableController.newInstance();
            controller.setEnabled(true);*/

            GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources())
                    .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
                    .setProgressBarImage(new ProgressBarDrawable())
                    .build();


            mGestureImageView.setController(controller);
            mGestureImageView.setHierarchy(hierarchy);

            //图片等比例缩放
            // getAvatarBitmap(imageRequest, controller, hierarchy, ClipPhotoActivity.this);
        }

    }

    @Override
    public void onContentChanged() {
        mTitle = (TextView) findViewById(R.id.photo_title);
        mGestureImageView = (ZoomableDraweeView) findViewById(R.id.gesture_iv);
        mBack = (ImageView) findViewById(R.id.btn_back);
        mBack.setOnClickListener(this);

        clip_image_borderview = (ClipImageBorderView) findViewById(R.id.clip_image_borderview);
        mCommit = (Button) findViewById(R.id.commit);
        mCommit.setOnClickListener(this);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle.setText(title);
    }

    private void initIntentParams() {
        Intent mIntent = getIntent();
        if (mIntent != null) {
            imgUrl = mIntent.getStringExtra(TAG);
        }

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_back) {
            finish();
        } else if (id == R.id.commit) {
            if (mGestureImageView != null) {
                Bitmap bm = mGestureImageView.clip();

                Log.e("bm", "bm:" + bm.toString());
                Intent resultIntent = new Intent();
                Bundle mBundle = new Bundle();
                mBundle.putParcelable(TAG, bm);
                resultIntent.putExtras(mBundle);
                setResult(101, resultIntent);
                finish();
            }
        }
    }


    private void getAvatarBitmap(ImageRequest imageRequest,
                                 final DefaultZoomableController controller, final GenericDraweeHierarchy hierarchy, final IBitmapShow callback) {

        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>> dataSource =
                imagePipeline.fetchDecodedImage(imageRequest, ClipPhotoActivity.this);
        dataSource.subscribe(new BaseBitmapDataSubscriber() {
            @Override
            protected void onNewResultImpl(@Nullable Bitmap bitmap) {
                if (bitmap != null) {
                    if (callback != null) {
                        callback.onBitmapLoadedSuccess(bitmap, controller, hierarchy);
                    }

                }
            }

            @Override
            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

            }
        }, CallerThreadExecutor.getInstance());
    }

    @Override
    public void onBitmapLoadedSuccess(Bitmap bm, DefaultZoomableController controller, GenericDraweeHierarchy hierarchy) {

        int bmWidth = bm.getWidth();
        int bmHeight = bm.getHeight();

        int newWidth = clip_image_borderview.getWidth() == 0 ? 200 : clip_image_borderview.getWidth();
        int newHeight = clip_image_borderview.getHeight() == 0 ? 200 : clip_image_borderview.getHeight();

        Log.e("bmWidth", "bmWidth:" + bmWidth + ",\nbmHeight:" + bmHeight +
                ",\nnewWidth:" + newWidth + ",\nnewHeight:" + newHeight);

        float scaleWidth = ((float) newWidth) / bmWidth;
        float scaleHeight = ((float) newHeight) / bmHeight;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, bmWidth, bmHeight, matrix, true);

        mGestureImageView.setZoomableController(controller);
        mGestureImageView.setHierarchy(hierarchy);
        mGestureImageView.setImageBitmap(newBm);

        mGestureImageView.setOnTouchListener(new View.OnTouchListener() {
            float baseValue = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        float x = last_x = event.getRawX();
                        float y = last_y = event.getRawY();
                        move = false;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (event.getPointerCount() == 2) {
                            //双指
                            float x1 = event.getX(0) - event.getX(1);
                            float y1 = event.getY(0) - event.getY(1);
                            //计算2点之间的距离
                            float value = (float) Math.sqrt(x1 * x1 + y1 * y1);
                            if (baseValue == 0) {
                                baseValue = value;
                            } else {
                                //由2点之间的距离来计算缩放比例
                                if ((value - baseValue) >= 10 || (baseValue - value) >= 10) {
                                    float scale = value / baseValue;
                                    img_scale(scale);
                                }
                            }
                        } else if (event.getPointerCount() == 1) {
                            //单指
                            float x2 = event.getRawX();
                            float y2 = event.getRawY();
                            x2 -= last_x;
                            y2 -= last_y;
                            if (x2 >= 10 || y2 >= 10 || x2 <= -10 || y2 <= -10) {
                                img_translate(x2, y2);
                                last_x = event.getRawX();
                                last_y = event.getRawY();
                            }
                        }
                        break;
                }
                return false;
            }
        });


    }

    /**
     * 平移
     *
     * @param x2
     * @param y2
     */
    private void img_translate(float x2, float y2) {

        if (mGestureImageView != null)
            mGestureImageView.img_translate(x2, y2);
    }

    /**
     * 缩放
     *
     * @param scale
     */
    private void img_scale(float scale) {
        if (mGestureImageView != null) {
            mGestureImageView.img_scale(scale);
        }
    }

}
