package com.common.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.support.annotation.DrawableRes;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.common.base.BaseActivity;
import com.common.toolbox.tracker.TrackEvent;
import com.common.widget.CameraView;
import com.common.widget.TopBar;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.io.File;

import tech.starwin.R;
import tech.starwin.impl.OnNoShakeClickListener;
import tech.starwin.utils.BitmapUtils;
import tech.starwin.utils.FileUtils;
import tech.starwin.utils.TrackEventHelper;
import tech.starwin.utils.context_utils.ActivityJumper;
import tech.starwin.utils.context_utils.EasyActivityResult;
import tech.starwin.utils.ui_utils.QMUIHelper;
import tech.starwin.utils.ui_utils.UIHelper;
import top.zibin.luban.Luban;

/**
 * Created by SiKang on 2018/9/25.
 */
public class TakePhotoActivity extends BaseActivity {
    public enum PhotoType {
        KTP("ktp_img.jpg"),
        WORK_CARD("work_card_img.jpg"),
        OTHERS_IMG("others_img.jpg");

        private String img_path;

        PhotoType(String path) {
            img_path = path;
        }

    }

    public static void startForResult(FragmentActivity activity, int requestCode, PhotoType type, @DrawableRes int previewMask, @DrawableRes int shootBtnImg, EasyActivityResult.OnResultListener result) {
        Intent intent = new ActivityJumper.Builder(activity, TakePhotoActivity.class)
                .put("photo_type", type.name())
                .put("preview_mask", previewMask)
                .put("shoot_btn_img", shootBtnImg)
                .toIntent();
        new EasyActivityResult(activity).startForResult(intent, requestCode, result);
    }

    PhotoType photoType;
    ImageView btnCapture;
    ImageView maskImv;
    Button mbtnCancel;
    CameraView cameraView;


    @Override
    public boolean useTopBar() {
        return false;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_take_photo;
    }


    @Override
    public void initView() {
        QMUIStatusBarHelper.translucent(this);

        TopBar topBar = findViewById(R.id.activity_take_photo_topbar);
        topBar.setStatusBarHeight(QMUIStatusBarHelper.getStatusbarHeight(this));
        topBar.toolBar().setTitle(R.string.text_take_photo);
        QMUIHelper.getTopbarCustomizer2().madeTopBar(topBar);
        QMUIHelper.getTopbarCustomizer2().initTopBar(topBar, this);

        btnCapture = findViewById(R.id.button_shoot);
        mbtnCancel = findViewById(R.id.button_cancel);
        cameraView = findViewById(R.id.cameraView);
        maskImv = findViewById(R.id.activity_takephoto_mask_imv);

        cameraView.setTargetPreviewSize(1280, 720);

        int mask = getIntent().getIntExtra("preview_mask", 0);
        int btnImg = getIntent().getIntExtra("shoot_btn_img", 0);
        if (mask != 0) {
            maskImv.setImageResource(mask);
        }
        if (btnImg != 0) {
            btnCapture.setImageResource(btnImg);
        }
        String type = getIntent().getStringExtra("photo_type");
        if (TextUtils.equals(type, PhotoType.KTP.name())) {
            TrackEventHelper.logEvent(TrackEvent.Click.KTP_SHOT);
            findViewById(R.id.imageview_id_frame).setVisibility(View.VISIBLE);
            photoType = PhotoType.KTP;
        } else if (TextUtils.equals(type, PhotoType.WORK_CARD.name())) {
            TrackEventHelper.logEvent(TrackEvent.Click.WORK_CARD_SHOT);
            photoType = PhotoType.WORK_CARD;
        } else {
            photoType = PhotoType.OTHERS_IMG;
        }

        ImageView screen_shot = findViewById(R.id.activity_take_photo_screen_shot);
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(screen_shot, "scaleX", 1f, 0.8f, 0.8f, 0.8f, 0.8f, 0.8f);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(screen_shot, "scaleY", 1f, 0.7f, 0.7f, 0.7f, 0.7f, 0.7f);
        animatorX.addListener(new ScreenShotAnimatorListener(screen_shot));
        animatorY.addListener(new ScreenShotAnimatorListener(screen_shot));
        animatorX.setDuration(500);
        animatorY.setDuration(500);

        UIHelper.bindClickListener(new OnNoShakeClickListener() {
            @Override
            public void onEventClick(View v) {
                if (v.getId() == R.id.button_shoot) {
                    cameraView.captureImage(bitmap -> {
                        runOnUiThread(() -> {
                            if (bitmap.getWidth() > bitmap.getHeight()) {
                                Matrix matrix = new Matrix();
                                matrix.postRotate(90f);
                                Bitmap newBmp =  Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                                screen_shot.setImageBitmap(newBmp);
                            } else {
                                screen_shot.setImageBitmap(bitmap);
                            }

                            animatorX.start();
                            animatorY.start();
                        });
                        try {
                            File image = FileUtils.getImageFile(getApplicationContext(), photoType.img_path);
                            if (!image.exists()) {
                                image.mkdir();
                            }

                            File file = BitmapUtils.saveBitmapToSDCard(bitmap, image, 100);
                            if (file != null) {
                                //压缩
                                file = Luban.with(TakePhotoActivity.this).load(file).get().get(0);
                                Intent intent = new Intent();
                                intent.putExtra("image_path", file.getAbsolutePath());
                                setResult(RESULT_OK, intent);
                                finish();
                            }

                        } catch (Exception e) {
                            setResult(RESULT_CANCELED);
                            finish();
                        }

                    });
                } else if (v.getId() == R.id.button_cancel) {
                    setResult(RESULT_CANCELED);
                    finish();
                }
            }
        }, mbtnCancel, btnCapture);

    }


    @Override
    protected void onResume() {
        cameraView.startPreview();
        super.onResume();
    }

    @Override
    protected void onStop() {
        cameraView.stopPreview();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        cameraView.release();
        super.onDestroy();
    }

    @Override
    public void onHttpSuccess(String action, Object result) {

    }


    private static class ScreenShotAnimatorListener implements Animator.AnimatorListener {
        ImageView screen_shot;

        ScreenShotAnimatorListener(ImageView screen_shot) {
            this.screen_shot = screen_shot;
        }

        @Override
        public void onAnimationStart(Animator animation) {
            screen_shot.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            screen_shot.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            screen_shot.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    }
}
