package com.wallpaper.perfectwallpaper.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.wallpaper.perfectwallpaper.adapter.ImageAdapter;
import com.wallpaper.perfectwallpaper.databinding.FragmentFavoriteBinding;
import com.wallpaper.perfectwallpaper.room.AppDatabase;
import com.wallpaper.perfectwallpaper.room.ImageEntry;
import com.wallpaper.perfectwallpaper.utils.DatabaseUtils;
import com.wallpaper.perfectwallpaper.utils.ItemDecoration;

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

public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private ImageAdapter adapter;
    private DatabaseUtils databaseUtils;

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

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


        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {

        databaseUtils = new DatabaseUtils(requireContext());

        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() {
        databaseUtils
                .getAllFavoriteList()
                .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;
    }
}