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

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


public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private FavoriteAdapter adapter;

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

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


        // 设置 RecyclerView
        setupRecyclerView();

        // 加载收藏的图片数据
        loadFavoriteImages();

        return binding.getRoot();
    }

    private void setupRecyclerView() {

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

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

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

    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 onDestroyView() {
        super.onDestroyView();
        // 在视图销毁时将绑定对象设为 null，防止内存泄漏
        binding = null;
    }


}