package com.adealink.weparty.commonui.mediapicker.imageselect.clip;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.ViewModelProvider;

import com.adealink.frame.util.DisplayUtil;
import com.adealink.frame.util.ImageUtil;
import com.adealink.weparty.R;
import com.adealink.weparty.commonui.BaseActivity;
import com.adealink.weparty.commonui.widget.CommonTopBar;

public class ClipImageActivity extends BaseActivity implements View.OnClickListener {

    // 不为空的情况下，保存截图到这个路径
    public static final String EXTRA_OUTPUT_IMAGE_PATH = "output_image_path";
    public static final String EXTRA_IMAGE_PATH = "image_path";
    public static final String EXTRA_HIGH_QUALITY = "extra_high_quality";

    public static final String ORIENTATION_IN_DEGREES = "orientation_in_degrees";
    public static final String RETURN_DATA = "return-data";
    public static final String RETURN_DATA_AS_BITMAP = "data";
    public static final String ACTION_INLINE_DATA = "inline-data";
    public static final int SELECT_IMAGE_FILE_CORRUPT = 512;
    public static final int CLIP_IMAGE_FAILED = 513;

    private static final String TAG = "clip_image";
    private static final int IMAGE_MAX_SIZE = 1024;

    private ClipImageView mClipIv;
    @Nullable
    private String mImagePath = null;
    private boolean mHightQuality = false;
    private Bitmap mBitmap = null;
    private Uri mSaveUri = null;
    @Nullable
    private String mOutputImagePath = "";
    private boolean mHasAlpha = false;
    private CommonTopBar mTopBar;

    private BitmapViewModel mBitmapViewModel;

    @Override
    public void initViews() {
        super.initViews();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_clip_image);
        mBitmapViewModel = new ViewModelProvider(this).get(BitmapViewModel.class);
        mClipIv = (ClipImageView) findViewById(R.id.clip_image_view);
        mClipIv.setHorizontalPadding(getIntent().getIntExtra(ClipImageView.HORIZONTAL_PADDING, 0));
        mClipIv.setWidthHeightRatio(getIntent().getDoubleExtra(ClipImageView.WIDTH_HEIGHT_RATIO, 0));
        findViewById(R.id.clip_image_discard).setOnClickListener(this);
        findViewById(R.id.clip_image_save).setOnClickListener(this);
        mTopBar = findViewById(R.id.top_bar);
        mTopBar.setBackCallback(() -> {
            setResult(RESULT_CANCELED);
            finish();
            return null;
        });
        mTopBar.setPadding(mTopBar.getPaddingLeft(), mTopBar.getPaddingTop() + DisplayUtil.getStatusBarHeight(this), mTopBar.getPaddingRight(), mTopBar.getPaddingBottom());
        ConstraintLayout.LayoutParams topBarLp = (ConstraintLayout.LayoutParams)mTopBar.getLayoutParams();
        topBarLp.height += DisplayUtil.getStatusBarHeight(this);
        mTopBar.setLayoutParams(topBarLp);

        mImagePath = getIntent().getStringExtra(EXTRA_IMAGE_PATH);
        mHightQuality = getIntent().getBooleanExtra(EXTRA_HIGH_QUALITY, false);
        mOutputImagePath = getIntent().getStringExtra(EXTRA_OUTPUT_IMAGE_PATH);
        if (TextUtils.isEmpty(mOutputImagePath)) mOutputImagePath = mImagePath;
        mSaveUri = ImageUtil.getImageUri(mOutputImagePath);
        mBitmap = ImageUtil.getBitmap(mImagePath);
        if (mBitmap == null) {

            //ͨ通知外面图片损坏
            setResult(SELECT_IMAGE_FILE_CORRUPT);
            finish();
            return;
        } else if (mBitmap.hasAlpha()) {
            mHasAlpha = true;
        }
        mClipIv.setImageBitmap(mBitmap);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public String getImagePath() {
        return mImagePath;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.clip_image_save) {
            Bitmap clippedBitmap;
            if (!mHightQuality) {
                clippedBitmap= mClipIv.clipImage();
            } else {
                clippedBitmap = mClipIv.clipImage2(mImagePath);
            }
            if (clippedBitmap == null) {

                setResult(CLIP_IMAGE_FAILED);
                finish();
                return;
            }
            Bundle myExtras = getIntent().getExtras(); // 返回bitmap对象
            if (myExtras != null && (myExtras.getParcelable("data") != null || myExtras.getBoolean(RETURN_DATA))) {
                Bundle extras = new Bundle();
                extras.putParcelable(RETURN_DATA_AS_BITMAP, clippedBitmap);
                setResult(RESULT_OK, (new Intent()).setAction(ACTION_INLINE_DATA).putExtras(extras));
                finish();
            } else { // 保存到指定的路径
                mBitmapViewModel.getSaveBitmapResult().observe(this, success -> {
                    if (success) {
                        Intent intent = new Intent(mSaveUri.toString());
                        intent.putExtra(EXTRA_IMAGE_PATH, mOutputImagePath);
                        intent.putExtra(ORIENTATION_IN_DEGREES, DisplayUtil.getOrientationInDegree());

                        setResult(RESULT_OK, intent);
                    } else {
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                });
                mBitmapViewModel.saveBitmap(clippedBitmap, mSaveUri);
            }
            setResult(RESULT_OK);
        } else if (id == R.id.clip_image_discard) {
            setResult(RESULT_CANCELED);
            finish();
        }
    }
}
