package com.naz.sdkdemo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.media.Image;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.common.util.concurrent.ListenableFuture;
import com.naz.sdkdemo.R;
import com.naz.sdkdemo.base.BaseActivity;
import com.naz.sdkdemo.base.CallbackNew;
import com.naz.sdkdemo.bean.AdBean;
import com.naz.sdkdemo.http.ApiHelper;
import com.naz.sdkdemo.picselect.SPictureSelector;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import butterknife.BindView;

/**
 * AD
 */
public class CaremaActivity extends BaseActivity {

    @BindView(R.id.previewView)
    PreviewView previewView;
    @BindView(R.id.take_picture)
    Button takePicture;

    String savePath;
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private ProcessCameraProvider cameraProvider;
    private ImageCapture imageCapture;

    @Override
    public int getLayoutResId() {
        return R.layout.carema_activity;
    }

    @Override
    public void initView() {
        checkPermissions();
        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePhoto();//取图识别
            }
        });

        ImageView photo = findViewById(R.id.photo);
        findViewById(R.id.show_picture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Glide.with(CaremaActivity.this)
                        .load(getImageFromPicturesDirectory(savePath))
                        .into(photo);
            }
        });
    }

    private void checkPermissions() {
        String[] PERMISSIONS_STORAGE = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,11);
        }else{
            startCamera();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraProvider.unbindAll();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==11){//获取权限后，开启摄像头
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                //启动相机
                startCamera();
            } else {
                Toast.makeText(CaremaActivity.this, "请打开存储权限和相机权限", Toast.LENGTH_SHORT).show();
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
        }
    }


    private void startCamera() {
        // 请求 CameraProvider
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        //检查 CameraProvider 可用性，验证它能否在视图创建后成功初始化
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                // No errors need to be handled for this Future.
                // This should never be reached.
            }
        }, ContextCompat.getMainExecutor(this));
    }

    //选择相机并绑定生命周期和用例
    private void bindPreview(@NonNull ProcessCameraProvider cp) {
        this.cameraProvider=cp;
        Preview preview = new Preview.Builder()
                .build();

        @SuppressLint("UnsafeOptInUsageError")
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)//CameraSelector.LENS_FACING_EXTERNAL
                .build();

//        preview.setSurfaceProvider(previewView.getSurfaceProvider());
        // 创建一个 ImageCapture 对象，用于拍摄照片。
        // 设置拍照模式为最小化延迟模式，这意味着拍照时将尽可能快地捕获图像。
        imageCapture = new ImageCapture.Builder()
                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                .build();
        cameraProvider.unbindAll();//解绑组件
        cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageCapture);
    }

    //拍照
    public void takePhoto() {
        Log.e("-------->","------>toTakePhoto");
        Log.e("OCR", "takePhoto");
        long timeStamp = System.currentTimeMillis();
        savePath = timeStamp+".jpg";
        // 通过 ContentValues 对象设置文件名和文件类型
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, timeStamp);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");

        imageCapture.takePicture(
                // 第一个参数 OutputFileOptions 指定了照片保存的位置和格式等信息。
                new ImageCapture.OutputFileOptions.Builder(
                        getContentResolver(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        contentValues
                ).build(),
                // 第二个参数 Executor 指定了保存照片时要运行的线程。
                ContextCompat.getMainExecutor(this),
                // 第三个参数 OnImageSavedCallback 指定了保存照片完成后的回调函数，可以在其中进行一些提示或其他操作。
                new ImageCapture.OnImageSavedCallback() {
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        Log.e("-------->","------>保存成功");
                        Toast.makeText(CaremaActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        Log.e("----------->","------->"+exception.getMessage());
                        Toast.makeText(CaremaActivity.this, "Error: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public static File getImageFromPicturesDirectory(String imageName) {
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(picturesDir, imageName);
        return imageFile.exists() ? imageFile : null;
    }
}
