package com.ads.cal.picturetranslate.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;

import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.PermissionUtil;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.SharedPreferencesUtil;
import com.ads.cal.picturetranslate.Util;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.google.common.util.concurrent.ListenableFuture;

import java.io.File;


@ExperimentalGetImage public class CameraActivity extends BaseActivity implements ImageAnalysis.Analyzer {

    private static final int SELECT_TAKE_PHONE = 1;
    private ImageCapture imageCapture;
    private ImageView imageView, selectPhone;
    private PreviewView mPreview;


    @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_camera);
        initView();
        initData();
        try {
            initCamera();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("AAAAAAA", e.getMessage());
        }
        SharedPreferencesUtil.saveString(this, SharedPreferencesUtil.KEY_FIRST_CLK_TAKE_PHOTO, "clk");
    }

    private void initView() {
        ImageView close = findViewById(R.id.close);
        close.setOnClickListener(v -> finish());
        mPreview = findViewById(R.id.preview);
        imageView = findViewById(R.id.take_photo);
        imageView.setOnClickListener(v -> startTakePhone());
        selectPhone = findViewById(R.id.select_phone);
        selectPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.checkSelfIMAGEPermission(CameraActivity.this, SELECT_TAKE_PHONE);
            }
        });
    }

    private void initData() {
        Uri firstImageUri = Util.getFirstImageUriFromGallery(this);
        if (firstImageUri == null) {
            return;
        }
        selectPhone.setImageURI(firstImageUri);

    }

    private void initCamera() {
        // 将Camera的生命周期和Activity绑定在一起（设定生命周期所有者），这样就不用手动控制相机的启动和关闭。
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            ProcessCameraProvider processCameraProvider = null;
            try {
                processCameraProvider = cameraProviderFuture.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Preview preview = new Preview.Builder().build();
            preview.setSurfaceProvider(mPreview.getSurfaceProvider());
            // 创建拍照所需的实例
            imageCapture = new ImageCapture.Builder()
                    .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                    .setJpegQuality(80).build();
            ImageAnalysis imageAnalysis = new ImageAnalysis.Builder().build();
            // Select back camera as a default
            CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
            try {
                if (null == processCameraProvider) {
                    return;
                }
                processCameraProvider.unbindAll();
                processCameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture, imageAnalysis);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, ContextCompat.getMainExecutor(this));
    }

    private void startTakePhone() {
        ImageCapture imageCapture = this.imageCapture;
        if (imageCapture == null) {
            return;
        }
        File photoFile = new File(getCacheDir(), "/" + System.currentTimeMillis() + ".jpeg");


        // 创建 output option 对象，用以指定照片的输出方式
        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions
                .Builder(photoFile)
                .build();

        imageView.setEnabled(false);
        // 执行takePicture（拍照）方法
        imageCapture.takePicture(outputFileOptions,
                ContextCompat.getMainExecutor(this),
                new ImageCapture.OnImageSavedCallback() {// 保存照片时的回调
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(CameraActivity.this, Uri.fromFile(photoFile));
                        imageView.setEnabled(true);
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        LogUtils.e("AAAAAA", exception.getMessage());
                        imageView.setEnabled(true);
                    }
                });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SELECT_TAKE_PHONE) {
            if (allPermissionsGranted(grantResults)) {
                PermissionUtil.toSystemPhoto(this, SELECT_TAKE_PHONE);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_enable_permissions), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean allPermissionsGranted(int[] grantResults) {
        return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 获取图片回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == SELECT_TAKE_PHONE) {
                Uri selectedImageUri = data.getData();
                PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(CameraActivity.this, selectedImageUri);
            } else {
                PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(CameraActivity.this, data.getData());
                LogUtils.e("uri", data.getData().toString());
            }
        }
    }



    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void analyze(@NonNull ImageProxy image) {
        LogUtils.e("AAAAAA", image.toString());
    }

    public static void startCameraActivity(Context context) {
        Intent intent = new Intent(context, CameraActivity.class);
        context.startActivity(intent);
    }
}
