package com.ar.artracestudio.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ar.artracestudio.adapter.ImportAdapter;
import com.ar.artracestudio.databinding.FragmentImportBinding;
import com.ar.artracestudio.room.AppDatabase;
import com.ar.artracestudio.room.ImageEntry;
import com.ar.artracestudio.room.ImageEntryDao;
import com.ar.artracestudio.utils.ItemDecoration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class ImportFragment extends Fragment implements ImportAdapter.OnHeaderClickListener {

    private FragmentImportBinding binding;

    private static final int PICK_IMAGE_REQUEST_CODE = 202; // 请求码，用于标识图片选择

    private ImportAdapter adapter; // 图片适配器
    private List<String> imagePaths = new ArrayList<>(); // 图片路径列表
    private AppDatabase appDatabase; // 数据库实例
    private ImageEntryDao imageEntryDao; // 图片条目 DAO

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentImportBinding.inflate(inflater, container, false);

        binding.recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.recyclerview.addItemDecoration(itemDecoration);
        adapter = new ImportAdapter(new ArrayList<>(), requireActivity(), this);
        binding.recyclerview.setAdapter(adapter);

        // 初始化数据库和 DAO
        appDatabase = AppDatabase.getInstance(requireContext());
        imageEntryDao = appDatabase.imageEntryDao();

        loadImages();

        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();

        adapter.notifyDataSetChanged();

    }

    private void loadImages() {
        // 获取数据库实例并调用查询方法
        AppDatabase.getInstance(requireContext())
                .imageEntryDao()
                .getAllImportImageLive()
                .observe(getViewLifecycleOwner(), new Observer<List<ImageEntry>>() {
                    @Override
                    public void onChanged(List<ImageEntry> imageEntries) {
                        adapter.updateData(imageEntries);
                    }
                });
    }

    /**
     * 打开图片选择器。
     */
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE); // 启动选择图片的活动
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 处理图片选择结果
        if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == getActivity().RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData(); // 获取选中的图片 URI
            if (selectedImageUri != null) {
                try {
                    if (isImageSizeAcceptable(selectedImageUri)) {
                        saveImageToInternalStorage(selectedImageUri); // 保存图片到内部存储
                    } else {
                        Toast.makeText(getContext(), "The image size is out of limit", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "Could not get image size: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 检查图片大小是否在允许范围内。
     *
     * @param uri 选中的图片 URI
     * @return 图片大小是否符合要求
     * @throws IOException 读取图片时可能抛出的异常
     */
    private boolean isImageSizeAcceptable(Uri uri) throws IOException {
        InputStream inputStream = requireContext().getContentResolver().openInputStream(uri);
        if (inputStream == null) {
            return false;
        }

        // 获取图片大小（字节）
        long fileSize = inputStream.available();
        inputStream.close();

        // 设置图片大小限制，单位为字节（例如，2MB = 2 * 1024 * 1024 字节）
        long maxFileSize = 10 * 1024 * 1024;

        return fileSize <= maxFileSize;
    }

    /**
     * 将选中的图片保存到内部存储。
     *
     * @param uri 选中的图片 URI
     */
    private void saveImageToInternalStorage(Uri uri) {
        try {
            // 从 URI 获取输入流
            InputStream inputStream = requireContext().getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream); // 解码图片

            if (bitmap == null) {
                Toast.makeText(getContext(), "Unable to load image", Toast.LENGTH_SHORT).show();
                return;
            }

            // 将图片保存到内部存储
            File internalStorageDir = requireContext().getFilesDir(); // 获取内部存储目录
            File imageFile = new File(internalStorageDir, System.currentTimeMillis() + ".jpg"); // 创建新图片文件
            FileOutputStream outputStream = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 将图片压缩并保存
            outputStream.close();
            inputStream.close();

            String imagePath = imageFile.getAbsolutePath(); // 获取图片绝对路径

            // 检查图片是否已经存在
            new Thread(() -> {
                if (isImageAlreadyExists(imagePath)) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(getContext(), "The image already exists", Toast.LENGTH_SHORT).show());
                    imageFile.delete(); // 删除重复的文件
                    return;
                }
                imagePaths.add(imagePath); // 添加图片路径到列表

                // 将图片路径插入数据库
                imageEntryDao.insert(new ImageEntry(false, true, imagePath));

            }).start();

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "Failed to save picture: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 检查图片是否已经存在。
     *
     * @param imagePath 图片路径
     * @return 图片是否已存在
     */
    private boolean isImageAlreadyExists(String imagePath) {
        File newImageFile = new File(imagePath);

        // 检查 imagePaths 列表
        for (String path : imagePaths) {
            File existingFile = new File(path);
            if (filesAreIdentical(existingFile, newImageFile)) {
                return true;
            }
        }

        // 检查数据库
        List<ImageEntry> imageEntries = imageEntryDao.getAllImportImage();
        for (ImageEntry imageEntry : imageEntries) {
            File existingFile = new File(imageEntry.getImagePath());
            if (filesAreIdentical(existingFile, newImageFile)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 比较两个文件是否相同。
     *
     * @param file1 文件1
     * @param file2 文件2
     * @return 文件是否相同
     */
    private boolean filesAreIdentical(File file1, File file2) {
        if (file1.length() != file2.length()) {
            return false; // 文件长度不同，则文件不同
        }
        // 可以根据需求进一步比较文件内容（例如，通过 MD5 哈希值或逐字节比较）
        return true;
    }

    @Override
    public void onHeaderClick() {
        openImagePicker();
    }

}