package com.lock.arcanvasart.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.lock.arcanvasart.Utils.ItemDecoration;
import com.lock.arcanvasart.adapter.CategoryAdapter;
import com.lock.arcanvasart.databinding.FragmentFavoriteBinding;
import com.lock.arcanvasart.room.AppDatabase;
import com.lock.arcanvasart.room.FavoriteImage;

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

public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private CategoryAdapter imageAdapter;

    @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() {
        // 初始化适配器，传入一个空列表
        imageAdapter = new CategoryAdapter(getContext(), new ArrayList<>());

        // 设置 RecyclerView 的布局管理器为 GridLayoutManager，列数为2
        binding.recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));

        // 设置适配器
        binding.recyclerview.setAdapter(imageAdapter);

        // 添加自定义的装饰，设置间距
        ItemDecoration itemDecoration = new ItemDecoration(12, 10, 9);
        binding.recyclerview.addItemDecoration(itemDecoration);
    }

    private void loadFavoriteImages() {
        // 获取数据库实例并调用查询方法
        AppDatabase.getInstance(getContext())
                .favoriteImageDao()
                .getFavoriteImages()
                .observe(getViewLifecycleOwner(), new Observer<List<FavoriteImage>>() {
                    @Override
                    public void onChanged(List<FavoriteImage> favoriteImages) {
                        if (favoriteImages.isEmpty()){
                            binding.backgroundImage.setVisibility(View.VISIBLE);
                            binding.backgroundText.setVisibility(View.VISIBLE);
                        }else {
                            binding.backgroundImage.setVisibility(View.GONE);
                            binding.backgroundText.setVisibility(View.GONE);
                        }
                        imageAdapter.updateData(favoriteImages);
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 在视图销毁时将绑定对象设为 null，防止内存泄漏
        binding = null;
    }
}
