package com.key.vibekeyboard.ui.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.data.database.entity.WallpaperInfo;
import com.key.vibekeyboard.ui.adapter.WallpaperAdapter;
import com.key.vibekeyboard.utils.ItemDecoration;
import com.key.vibekeyboard.viewmodel.WallpaperViewModel;
import com.key.vibekeyboard.databinding.FragmentFavoriteBinding;

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


public class FavoriteFragment extends Fragment {

    private FragmentFavoriteBinding binding;
    private WallpaperAdapter 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 WallpaperAdapter(requireContext(), wallpaperInfoList);
        binding.favoriteRecyclerview.setAdapter(adapter);

        binding.favoriteRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
        binding.favoriteRecyclerview.addItemDecoration(new ItemDecoration(16, 19, 10));

        WallpaperViewModel wallpaperViewModel = new ViewModelProvider(this).get(WallpaperViewModel.class);

        wallpaperViewModel.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;
    }
}

