package com.app.paintingstool.myact;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
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.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.paintingstool.R;
import com.app.paintingstool.databinding.ActivityImporImageBinding;
import com.app.paintingstool.myadapter.ImageAdapter1;
import com.app.paintingstool.myuntils.ImageItem;
import com.app.paintingstool.myuntils.MyItemDecoration;
import com.app.paintingstool.myuntils.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class ImporImageActivity extends AppCompatActivity {
    private ActivityImporImageBinding binding;

    private List<ImageItem> imageList;
    private ImageAdapter1 imageAdapter1;
    String fileName;
    String fileExtension;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityImporImageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.back.setOnClickListener(v -> {
            finish();
        });
        imageList = new ArrayList<>();
        imageAdapter1 = new ImageAdapter1(imageList, this, this);
        importImage();
        loadImageList();
        RecyclerView recyclerView = findViewById(R.id.recycler_view_import);
        recyclerView.setAdapter(imageAdapter1);
        recyclerView.addItemDecoration(new MyItemDecoration(this, 16, 24, 20));
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));

    }



    private void importImage() {
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Intent data = result.getData();
                Uri imageUri = data.getData();
                if (imageUri == null) return;
                new Thread(() -> {
                    try {
                        String mimeType = getContentResolver().getType(imageUri);
                        fileExtension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
                        fileName = "image_" + System.currentTimeMillis() + "." + fileExtension;
                        File outputFile = new File(getFilesDir(), fileName);
                        InputStream inputStream = null;
                        OutputStream outputStream = null;
                        try {
                            inputStream = getContentResolver().openInputStream(imageUri);
                            double v = Utils.convertBytesToMB(inputStream.available());
                            Log.d("----------","-----------"+v);
                            if (v >= 5) {
                                runOnUiThread(() -> {
                                    Toast.makeText(ImporImageActivity.this, getString(R.string.im_big), Toast.LENGTH_SHORT).show();
                                });
                                return;
                            }

                            outputStream = new FileOutputStream(outputFile);
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = inputStream.read(buffer)) > 0) {
                                outputStream.write(buffer, 0, length);
                            }
                        } catch (Exception e) {

                        } finally {
                            if (inputStream != null) {
                                inputStream.close();
                            }
                            if (outputStream != null) {
                                outputStream.close();
                            }
                        }
                        runOnUiThread(() -> {
                            Glide.with(this).load(outputFile)
                                    .into(new CustomTarget<Drawable>() {
                                        @Override
                                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                            imageList.add(new ImageItem(outputFile.getAbsolutePath()));
                                            imageAdapter1.notifyItemInserted(imageList.size() - 1);
                                            binding.reDef.setVisibility(View.GONE);
                                            saveImageList();
                                        }

                                        @Override
                                        public void onLoadCleared(@Nullable Drawable placeholder) {
                                        }
                                    });
                        });
                    } catch (Exception e) {
                    }
                }).start();
            }
        });

        binding.imgImport.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intentActivityResultLauncher.launch(intent);

        });
    }

    private void saveImageList() {
        if (imageList.isEmpty()) {
            return;
        }
        try {
            JSONArray jsonArray = new JSONArray();
            for (ImageItem imageItem : imageList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("imagePath", imageItem.imagePath);
                jsonArray.put(jsonObject);
            }
            FileOutputStream fileOutputStream = openFileOutput("image_list.json", Context.MODE_PRIVATE);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            outputStreamWriter.write(jsonArray.toString());
            outputStreamWriter.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

    private void loadImageList() {
        File file = new File(getFilesDir(), "image_list.json");
        if (!file.exists()) {
            return; // 如果文件不存在，则不加载数据
        } else {
            try {
                FileInputStream fileInputStream = openFileInput("image_list.json");
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                binding.reDef.setVisibility(View.GONE);
                bufferedReader.close();
                JSONArray jsonArray = new JSONArray(stringBuilder.toString());
                imageList.clear(); // 清空 imageList，避免重复添加
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String imagePath = jsonObject.getString("imagePath");
                    imageList.add(new ImageItem(imagePath));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }
}