package com.ar.arsketch.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.arsketch.R;
import com.ar.arsketch.adapter.ImageAdapter;
import com.ar.arsketch.databinding.FragmentFavoriteBinding;
import com.ar.arsketch.room.AppDatabase;
import com.ar.arsketch.room.ImageEntry;
import com.ar.arsketch.utils.ItemDecoration;

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

public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private ImageAdapter adapter;

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

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


        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {

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

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

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

    }

    private void initEvent() {
        loadFavoriteImages();
    }

    private void loadFavoriteImages() {
        AppDatabase.getInstance(requireContext())
                .imageEntryDao()
                .getAllFavoriteLive()
                .observe(getViewLifecycleOwner(), new Observer<List<ImageEntry>>() {
                    @Override
                    public void onChanged(List<ImageEntry> imageEntries) {
                        if (imageEntries.isEmpty()) {
                            binding.backgroundImage.setVisibility(View.VISIBLE);
                            binding.backgroundText.setVisibility(View.VISIBLE);
                        } else {
                            binding.backgroundImage.setVisibility(View.GONE);
                            binding.backgroundText.setVisibility(View.GONE);
                        }
                        adapter.updateData(imageEntries);
                    }
                });
    }

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