package com.ar.paintar.fragment;

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

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

import com.ar.paintar.adapter.PhotoAdapter;
import com.ar.paintar.databinding.FragmentFavoriteBinding;
import com.ar.paintar.room.AppDatabase;
import com.ar.paintar.room.ImageData;
import com.ar.paintar.utils.DatabaseUtil;
import com.ar.paintar.utils.ItemDecoration;

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

public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private PhotoAdapter adapter;
    private DatabaseUtil databaseUtil;

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

        binding = FragmentFavoriteBinding.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 PhotoAdapter(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() {
        databaseUtil
                .getAllFavoriteImageData()
                .observe(getViewLifecycleOwner(), new Observer<List<ImageData>>() {
                    @Override
                    public void onChanged(List<ImageData> imageEntries) {
                        if (imageEntries.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateData(imageEntries);
                    }
                });
    }

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