package com.ads.cal.picturetranslate.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
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.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.google.mlkit.vision.common.InputImage;

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


@ExperimentalGetImage public class PictureTranslateShowPhotoActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // 隐藏状态栏和虚拟导航栏
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );

        // 隐藏虚拟导航栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_photon);
        initView();
        initData();
    }

    private ImageView imageView;

    private void initView() {
        ImageView close = findViewById(R.id.close);
        close.setOnClickListener(v -> finish());
        LinearLayout crop = findViewById(R.id.crop);
        crop.setOnClickListener(v -> PictureTranslateCutOutPhotoActivity.startCutOutPhotoActivity(this, uri));

        LinearLayout extract = findViewById(R.id.extract);
        extract.setOnClickListener(v -> {
            if (path == null) {
                return;
            }
            showLoadingFragment(new LoadingFragment());
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap == null) {
                hideLoadingFragment();
                return;
            }
            Bitmap rotatedBitmap = rotateBitmapIfNecessary(bitmap, exif);

            // 保存旋转后的图片
            String resultPath = saveRotatedImage(rotatedBitmap);

            if (!resultPath.isEmpty()) {
                translate(rotatedBitmap, resultPath);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_unable_to_save_picture), Toast.LENGTH_SHORT).show();
            }

            // 释放位图资源
            bitmap.recycle();
        });
        imageView = findViewById(R.id.bg);
    }

    private void translate(Bitmap bitmap, String path) {
        if (bitmap == null) {
            hideLoadingFragment();
            return;
        }
        PictureTranslateUtils.init().translateStandard(InputImage.fromBitmap(bitmap, 0),
                text -> {
                    hideLoadingFragment();
                    LogUtils.e("AAAAAA", text.getText());
                    PictureTranslateBean bean = new PictureTranslateBean();
                    bean.setImageUrl(path);
                    bean.setTitle(text.getText());
                    bean.setTime(System.currentTimeMillis());
                    PictureTranslateResultActivity.startPictureTranslateResultActivity(PictureTranslateShowPhotoActivity.this, bean);
                    finish();
                    if (bitmap.isRecycled()) {
                        return;
                    }
                    bitmap.recycle();
                },
                e -> {
                    hideLoadingFragment();
                    LogUtils.e("AAAAAA", e.getMessage());
                    if (bitmap.isRecycled()) {
                        return;
                    }
                    bitmap.recycle();
                });
    }

    private Uri uri = null;
    private String path;

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            uri = intent.getParcelableExtra("uri");
        }
        if (uri == null) {
            return;
        }
        path = Util.getFileFromUri(this, uri);
        if (path == null || path.isEmpty()) {
            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();
            }
            setImageBitmap(bitmap, exif);
        }
    }

    public void setImageBitmap(Bitmap bitmap, ExifInterface exif) {
        if (bitmap == null) {
            return;
        }

        Matrix matrix = new Matrix();
        int orientation = exif != null ? exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) : ExifInterface.ORIENTATION_NORMAL;
        int rotate = getRotateValueForOrientation(orientation);

        if (rotate != 0) {
            matrix.postRotate(rotate);
        }

        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        imageView.setImageBitmap(rotatedBitmap);
        if (bitmap.isRecycled()) {
            return;
        }
        bitmap.recycle();
    }

    private Bitmap rotateBitmapIfNecessary(Bitmap bitmap, ExifInterface exif) {
        if (exif == null) {
            return bitmap;
        }

        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        int rotate = getRotateValueForOrientation(orientation);

        if (rotate != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(rotate);
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }

        return bitmap;
    }

    private int getRotateValueForOrientation(int orientation) {
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return 90;
            case ExifInterface.ORIENTATION_ROTATE_180:
                return 180;
            case ExifInterface.ORIENTATION_ROTATE_270:
                return 270;
            default:
                return 0;
        }
    }

    private String saveRotatedImage(Bitmap rotatedBitmap) {
        String path = getCacheDir().getPath();
        String resultPath = "";
        OutputStream outputStream = null;

        try {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, System.currentTimeMillis() + ".jpeg");

            outputStream = new FileOutputStream(file);

            if (rotatedBitmap != null) {
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                resultPath = file.getPath();
            }
        } catch (IOException e) {
            LogUtils.e("Exception", e.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    LogUtils.e("Exception", e.getMessage());
                }
            }
        }

        return resultPath;
    }

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