package com.ardraw.ardrawinggallery.fragment;

import android.os.Bundle;

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

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

import com.ardraw.ardrawinggallery.R;
import com.ardraw.ardrawinggallery.adapter.GalleryAdapter;
import com.ardraw.ardrawinggallery.databinding.FragmentLikeBinding;
import com.ardraw.ardrawinggallery.room.ArData;
import com.ardraw.ardrawinggallery.util.DatabaseUtil;
import com.ardraw.ardrawinggallery.util.ItemDecoration;

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

public class LikeFragment extends Fragment {
    private FragmentLikeBinding binding;
    private GalleryAdapter adapter;
    private DatabaseUtil databaseUtil;

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

        binding = FragmentLikeBinding.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() {
        loadAllFavorite();
    }

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

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