package com.ads.cal.picturetranslate.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;

import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.MessageEvent;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.PictureTranslateUtils;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.Util;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.ads.cal.picturetranslate.bean.PictureTranslateBean;
import com.ads.cal.picturetranslate.fragment.LoadingFragment;
import com.edmodo.cropper.CropImageView;
import com.google.mlkit.vision.common.InputImage;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@ExperimentalGetImage
public class PictureTranslateCutOutPhotoActivity extends BaseActivity {


    private CropImageView cropImageView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            finish();
            return;
        }
        setContentView(R.layout.activity_cutoutphoto);
        initView();
        initData();
    }

    private void initView() {
        cropImageView = findViewById(R.id.crop);
        ImageView close = findViewById(R.id.back);
        LinearLayout ok = findViewById(R.id.ok_crop);
        close.setOnClickListener(v -> {
            finish();
        });
        ok.setOnClickListener(v -> {
            showLoadingFragment(new LoadingFragment());
            Bitmap cropperBitmap = cropImageView.getCroppedImage();
            // 图像名称
            String path = getCacheDir().getPath();
            String resultPath = saveImage(path, cropperBitmap);
            translate(cropperBitmap, resultPath);
        });
    }

    private void translate(Bitmap bitmap, String path) {
        if (bitmap == null) {
            hideLoadingFragment();
            return;
        }
        PictureTranslateUtils.init().translateChinese(InputImage.fromBitmap(bitmap, 0),
                text -> {
                    hideLoadingFragment();
                    LogUtils.e("AAAAAA", text.getText());
                    PictureApplication.getDataBaseManager().insertData(path, text.getText(), System.currentTimeMillis());
                    PictureTranslateBean bean = new PictureTranslateBean();
                    bean.setImageUrl(path);
                    bean.setTitle(text.getText());
                    bean.setTime(System.currentTimeMillis());
                    PictureTranslateResultActivity.startPictureTranslateResultActivity(PictureTranslateCutOutPhotoActivity.this, bean);
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.FINISH_ACTIVITY, null));
                    finish();
                    if (bitmap.isRecycled()) {
                        return;
                    }
                    bitmap.recycle();
                },
                e -> {
                    hideLoadingFragment();
                    LogUtils.e("AAAAAA", e.getMessage());
                    if (bitmap.isRecycled()) {
                        return;
                    }
                    bitmap.recycle();
                });
    }

    private void initData() {
        Intent intent = getIntent();
        Uri uri = null;
        if (intent != null) {
            uri = intent.getParcelableExtra("uri");
        }
        if (uri == null) {
            return;
        }
        String path = Util.getFileFromUri(this, uri);
        if (TextUtils.isEmpty(path)) {
            Toast.makeText(this, getString(R.string.app_toast_the_file_is_corrupted), Toast.LENGTH_SHORT).show();
        } else {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            cropImageView.setImageBitmap(bitmap, exif);
        }
    }

    /**
     * 存储图像
     */
    private String saveImage(String path, Bitmap source) {
        LogUtils.e("AAAAAAAAA", path);
        OutputStream outputStream = null;
        File file;
        try {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = new File(path, System.currentTimeMillis() + ".jpeg");
            LogUtils.e("AAAAAAAAA", file.getPath());
            if (file.createNewFile()) {
                outputStream = new FileOutputStream(file);
                if (source != null) {
                    source.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                }
            }
        } catch (IOException e) {
            LogUtils.e("AAAAAAAA", e.getMessage());
            return "";
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Throwable t) {
                }
            }
        }

        return file.getPath();
    }

    public static void startCutOutPhotoActivity(Context context, Uri uri) {
        Intent intent = new Intent(context, PictureTranslateCutOutPhotoActivity.class);
        intent.putExtra("uri", uri);
        context.startActivity(intent);
    }
}
