package com.ar.ardrawingboard.ui.fragment;

import android.os.Bundle;

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

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ar.ardrawingboard.ui.adapter.FavoriteAndCategoryAdapter;
import com.ar.ardrawingboard.databinding.FragmentFavoriteBinding;
import com.ar.ardrawingboard.room.AppDatabase;
import com.ar.ardrawingboard.room.BoardEntry;
import com.ar.ardrawingboard.util.ItemDecoration;

import java.util.ArrayList;
import java.util.List;

public class FavoriteFragment extends Fragment {
    private FragmentFavoriteBinding binding;
    private FavoriteAndCategoryAdapter adapter;

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

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

        setupRecyclerView();
        loadFavoriteImages();

        return binding.getRoot();
    }

    private void setupRecyclerView() {
        binding.recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new FavoriteAndCategoryAdapter(requireContext(),new ArrayList<>());
        binding.recyclerview.setAdapter(adapter);

        binding.recyclerview.addItemDecoration(new ItemDecoration(16, 19, 10));
    }

    private void loadFavoriteImages() {
        AppDatabase.getInstance(requireContext())
                .boardEntryDao()
                .getFavorite()
                .observe(getViewLifecycleOwner(), new Observer<List<BoardEntry>>() {
                    @Override
                    public void onChanged(List<BoardEntry> imageEntries) {
                        if (imageEntries.isEmpty()) {
                            binding.backgroundText.setVisibility(View.VISIBLE);
                        } else {
                            binding.backgroundText.setVisibility(View.GONE);
                        }
                        adapter.refreshFavorites(imageEntries);
                    }
                });
    }

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