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.EditText;
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.TopOnItAdManager;
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.AgainFragment;
import com.ads.cal.picturetranslate.fragment.LoadingFragment;
import com.google.mlkit.vision.common.InputImage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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();
        EventBus.getDefault().register(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && event.type == MessageEvent.FINISH_ACTIVITY) {
            finish();
        }
    }

    private ImageView imageView;
    private LinearLayout crop, extract;

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

        extract = findViewById(R.id.extract);
        extract.setOnClickListener(v -> {
            extractFunction();
        });
        imageView = findViewById(R.id.bg);
    }

    public void extractFunction() {
        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, bitmap);
            crop.setVisibility(View.GONE);
            extract.setVisibility(View.GONE);
        } else {
            Toast.makeText(this, getString(R.string.app_toast_unable_to_save_picture), Toast.LENGTH_SHORT).show();
        }
    }

    private void translate(Bitmap bitmap, String path, Bitmap sBitmap) {
        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());
                    PictureTranslateResultActivity.startPictureTranslateResultActivity(PictureTranslateShowPhotoActivity.this, bean);
                    finish();
                    if (bitmap.isRecycled()) {
                        return;
                    }
                    bitmap.recycle();
                    if (sBitmap == null || sBitmap.isRecycled()) {
                        return;
                    }
                    sBitmap.recycle();
                },
                e -> {
                    crop.setVisibility(View.VISIBLE);
                    extract.setVisibility(View.VISIBLE);
                    hideLoadingFragment();
                    showFragment(new AgainFragment(), android.R.id.content);
                    LogUtils.e("AAAAAA", e.getMessage());
                    if (bitmap.isRecycled()) {
                        return;
                    }
                    bitmap.recycle();
                    if (sBitmap == null || sBitmap.isRecycled()) {
                        return;
                    }
                    sBitmap.recycle();
                });
    }

    private Uri uri = null;
    private String path;
    private Bitmap bitmap;

    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 = 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 || bitmap.isRecycled()) {
            return;
        }

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

        LogUtils.e(rotate + "");
        if (rotate != 0) {
            matrix.postRotate(rotate);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            if (rotatedBitmap != null) {
                imageView.setImageBitmap(rotatedBitmap);
            }
            if (bitmap.isRecycled()) {
                return;
            }
            try {
                bitmap.recycle();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            imageView.setImageBitmap(bitmap);
        }
    }

    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;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        imageView.setImageDrawable(null);
        imageView.setImageBitmap(null);
        if (bitmap == null || bitmap.isRecycled()) {
            return;
        }
        bitmap.recycle();
        EventBus.getDefault().unregister(this);
    }

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