package com.key.vibekeyboard.Fragment;

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

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

import com.key.vibekeyboard.Adapter.FavoriteRecyclerViewAdapter;
import com.key.vibekeyboard.Room.WallpaperInfo;
import com.key.vibekeyboard.Utils.ItemDecoration;
import com.key.vibekeyboard.ViewModel.FavoriteViewModel;
import com.key.vibekeyboard.databinding.FragmentFavoriteBinding;

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


public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private FavoriteRecyclerViewAdapter adapter;
    private final List<WallpaperInfo> wallpaperInfoList = new ArrayList<>();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFavoriteBinding.inflate(inflater, container, false);

        adapter = new FavoriteRecyclerViewAdapter(requireContext(), wallpaperInfoList);
        binding.favoriteRecyclerview.setAdapter(adapter);

        // 初始化 RecyclerView 和 LayoutManager
        binding.favoriteRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
        binding.favoriteRecyclerview.addItemDecoration(new ItemDecoration(16, 19, 10));

        // 获取 ViewModel 实例
        FavoriteViewModel favoriteViewModel = new ViewModelProvider(this).get(FavoriteViewModel.class);

        // 监听 LiveData 的变化并更新 RecyclerView
        favoriteViewModel.getFavoriteList().observe(getViewLifecycleOwner(), new Observer<List<WallpaperInfo>>() {
            @Override
            public void onChanged(List<WallpaperInfo> wallpaperInfoList) {

                if (wallpaperInfoList.isEmpty()) {
                    binding.backgroundImage.setVisibility(View.VISIBLE);
                    binding.backgroundText.setVisibility(View.VISIBLE);
                } else {
                    binding.backgroundImage.setVisibility(View.GONE);
                    binding.backgroundText.setVisibility(View.GONE);
                }
                adapter.updateList(wallpaperInfoList);
            }
        });

        return binding.getRoot();
    }

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

