package com.ardraw.ardrawinggallery.fragment;

import android.app.Activity;
import android.content.Intent;
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.ardraw.ardrawinggallery.adapter.GalleryAdapter;
import com.ardraw.ardrawinggallery.databinding.FragmentPhotoBinding;
import com.ardraw.ardrawinggallery.room.ArData;
import com.ardraw.ardrawinggallery.util.DatabaseUtil;
import com.ardraw.ardrawinggallery.util.ImageUtils;
import com.ardraw.ardrawinggallery.util.ItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PhotoFragment extends Fragment {
    private static final int PICK_IMAGE_REQUEST_CODE = 202;
    private FragmentPhotoBinding binding;
    private GalleryAdapter adapter;
    private DatabaseUtil databaseUtil;
    private final List<String> imagePaths = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentPhotoBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        databaseUtil = new DatabaseUtil(requireContext());

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new GalleryAdapter(new ArrayList<>(), requireContext(), 1);
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(35, 15, 20);
        binding.recyclerView.addItemDecoration(itemDecoration);
    }

    private void initEvent() {
        binding.add.setOnClickListener(v -> {
            openImagePicker();
        });

        loadAllImportImage();
    }

    private void loadAllImportImage() {
        databaseUtil
                .getAllImportLive()
                .observe(getViewLifecycleOwner(), new Observer<List<ArData>>() {
                    @Override
                    public void onChanged(List<ArData> arData) {
                        if (arData.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateData(arData);
                    }
                });
    }

    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 == Activity.RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                processImage(selectedImageUri);
            }
        }
    }

    private void processImage(Uri imageUri) {
        try {
            if (ImageUtils.isImageSizeValid(imageUri, requireContext())) {
                ImageUtils.saveImage(imageUri, imagePaths, databaseUtil, requireContext(), requireActivity());
            } else {
                showToast("The image size is out of limit");
            }
        } catch (IOException e) {
            e.printStackTrace();
            showToast("Could not get image size: " + e.getMessage());
        }
    }

    private void showToast(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}