package com.app.paintingstool.myact;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.app.paintingstool.R;
import com.app.paintingstool.databinding.ActivityCarmelBinding;
import com.app.paintingstool.myuntils.Keys;
import com.app.paintingstool.myuntils.Utils;
import com.google.common.util.concurrent.ListenableFuture;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class CarmelActivity extends AppCompatActivity implements View.OnTouchListener, View.OnClickListener {
    private ActivityCarmelBinding binding;
    private Matrix startMatrix;
    private final Matrix endMatrix = new Matrix();//变化后的矩阵
    private final PointF startPointF = new PointF();//初始坐标
    private float distance;//初始距离
    private float scaleMultiple;//缩放倍数
    private final static int MODE_NONE = 0;
    private final static int MODE_DRAG = 1;
    private final static int MODE_SCALE = 2;
    private int MODE = MODE_NONE;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;


    private CameraSelector cameraSelector;
    private String[] permissions;
    private ImageCapture imageCapture;
    private boolean hasPermission = false;
    private int range;
    private Camera camera;
    private String curBitmapPath, imagePath, imagePathOrAssetPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityCarmelBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        curBitmapPath = getIntent().getStringExtra("nameCa");
        imagePath = getIntent().getStringExtra("imagePath");
        imagePathOrAssetPath = getIntent().getStringExtra("imagePathOrAssetPath");
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Uri imageUri = result.getData().getData();
                if (imageUri == null) return;
                new Thread(() -> {
                    InputStream putStream = null;
                    try {
                        putStream = getContentResolver().openInputStream(imageUri);
                        double v = Utils.convertBytesToMB(putStream.available());
                        runOnUiThread(() -> {
                            if (v >= 5) {
                                Toast.makeText(CarmelActivity.this, getString(R.string.im_big), Toast.LENGTH_SHORT).show();
                            } else {
                                binding.image.setImageURI(imageUri);
                            }
                        });
                        putStream.close();
                    } catch (IOException e) {

                    }
                }).start();


            }

        });
        init();
        initClick();
        binding.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float v = (seekBar.getMax() - progress) / 10.0f;
                binding.image.setAlpha(v);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v.equals(binding.back)) {
            finish();
        } else {
            if (!hasPermission) {
                showNoPermission();
                return;
            }
            if (v.equals(binding.imFlash)) {
                boolean selected = binding.imFlash.isSelected();
                binding.imFlash.setSelected(!selected);
                camera.getCameraControl().enableTorch(!selected);
            } else if (v.equals(binding.imPhoto)) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intentActivityResultLauncher.launch(intent);
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init() {
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
        permissions = new String[]{android.Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            permissions = new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }
        if (!checkPermission()) {
            hasPermission = false;
            binding.image.setOnTouchListener(null);
            ActivityCompat.requestPermissions(this, permissions, 0);
        } else {
            hasPermission = true;
            binding.image.setOnTouchListener(this);
            startCamera();
        }
    }

    private void initClick() {
        binding.back.setOnClickListener(this);
        binding.imFlash.setOnClickListener(this);
        binding.imPhoto.setOnClickListener(this);
    }

    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> future = ProcessCameraProvider.getInstance(this);
        future.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = future.get();
                Preview preview = new Preview.Builder().build();
                cameraProvider.unbindAll();
                ImageCapture.Builder builder1 = new ImageCapture.Builder();
                imageCapture = builder1.build();
                camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture);
                range = Keys.getRange(camera);
                preview.setSurfaceProvider(binding.preview.getSurfaceProvider());
                if (imagePathOrAssetPath != null) {
                    if (!isAssetFile(imagePathOrAssetPath)) {
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePathOrAssetPath);
                        binding.image.setImageBitmap(bitmap);
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        onInitIm(width, height);
                    } else {
                        Bitmap bitmap = Keys.loadImageFromAssets(this, imagePathOrAssetPath);
                        binding.image.setImageBitmap(bitmap);
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        onInitIm(width, height);
                    }
                } else {
                    if (imagePath != null) {
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                        binding.image.setImageBitmap(bitmap);
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        onInitIm(width, height);
                    } else {
                        if (curBitmapPath != null) {
                            Bitmap bitmap = Keys.loadImageFromAssets(this, curBitmapPath);
                            binding.image.setImageBitmap(bitmap);
                            int width = bitmap.getWidth();
                            int height = bitmap.getHeight();
                            onInitIm(width, height);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private boolean isAssetFile(String imagePath) {
        AssetManager assetManager = this.getAssets();
        try {
            InputStream inputStream = assetManager.open(imagePath);
            inputStream.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (checkPermission()) {
                hasPermission = true;
                binding.image.setOnTouchListener(this);
                startCamera();
            } else {
                hasPermission = false;
                binding.image.setOnTouchListener(null);
            }

        }
    }

    private boolean checkPermission() {
        boolean result = true;
        for (String per : permissions) {
            if (ActivityCompat.checkSelfPermission(this, per) != PackageManager.PERMISSION_GRANTED) {
                result = false;
            }
        }
        return result;

    }

    private void onInitIm(float imW, float imH) {
        Point screen = Keys.getScreen(this);
        float newX = screen.x / 2f - imW / 2;
        float newY = screen.y / 2f - imH / 2;
        startMatrix = new Matrix();
        startMatrix.postTranslate(newX, newY);
        binding.image.setImageMatrix(startMatrix);
    }

    private void showNoPermission() {
        Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction() & event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                startMatrix.set(binding.image.getImageMatrix());
                endMatrix.set(binding.image.getImageMatrix());
                startPointF.set(event.getX(), event.getY());
                MODE = MODE_DRAG;

                break;
            case MotionEvent.ACTION_POINTER_DOWN:

                startMatrix.set(endMatrix);

                distance = Keys.getDistance(event);

                MODE = MODE_SCALE;

                break;
            case MotionEvent.ACTION_MOVE://滑动（单+双）
                if (MODE == MODE_DRAG) {//单指滑动时
                    endMatrix.set(startMatrix);
                    //向矩阵传入位移距离
                    endMatrix.postTranslate(event.getX() - startPointF.x, event.getY() - startPointF.y);
                    Log.d("---------------tt", "------ACTION_MOVE-----x=" + event.getX() + "------y=" + event.getY());
                } else if (MODE == MODE_SCALE) {//双指滑动时
                    //计算缩放倍数
                    scaleMultiple = Keys.getDistance(event) / distance;
                    //获取初始矩阵
                    endMatrix.set(startMatrix);
                    //向矩阵传入缩放倍数
                    endMatrix.postScale(scaleMultiple, scaleMultiple, startPointF.x, startPointF.y);
                }
                break;
            case MotionEvent.ACTION_UP://单指离开
            case MotionEvent.ACTION_POINTER_UP://双指离开
                //手指离开后，重置状态
                MODE = MODE_NONE;

                break;
        }
        //事件结束后，把矩阵的变化同步到ImageView上
        binding.image.setImageMatrix(endMatrix);
        return true;
    }
}