package com.cartoon.wallpapers.live.ui;

import android.view.View;

import androidx.lifecycle.Observer;
import androidx.paging.PagingData;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cartoon.wallpapers.live.ada.Like;
import com.cartoon.wallpapers.live.base.BaseFragment;
import com.cartoon.wallpapers.live.databinding.LikeFragmentBinding;
import com.cartoon.wallpapers.live.listener.LikeUpdateListener;
import com.cartoon.wallpapers.live.mydata.FavoriteData;
import com.cartoon.wallpapers.live.utils.Decoration;
import com.cartoon.wallpapers.live.utils.ObjectBoxManager;
import com.cartoon.wallpapers.live.vm.ViewModelLike;

import java.util.List;

import io.objectbox.reactive.DataSubscription;

public class LikeFragment extends BaseFragment<LikeFragmentBinding> {
    private DataSubscription dataSubscription;

    private ViewModelLike viewModelLike;


    public LikeFragment() {

    }

    public static LikeFragment newInstance() {
        LikeFragment fragment = new LikeFragment();
        return fragment;
    }




    @Override
    protected LikeFragmentBinding getFragmentVb() {
        return LikeFragmentBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        Like likeAdapter = new Like(requireActivity());
        Vb.recycler.setAdapter(likeAdapter);
        Vb.recycler.setLayoutManager(new GridLayoutManager(requireContext(), 2, RecyclerView.VERTICAL, false));
        Vb.recycler.addItemDecoration(new Decoration(requireContext(), 8, 8, 8));
        viewModelLike = getFragmentScopeViewModel(ViewModelLike.class);

        viewModelLike.likeLiveData.observe(getViewLifecycleOwner(), new Observer<PagingData<FavoriteData>>() {
            @Override
            public void onChanged(PagingData<FavoriteData> data) {
                likeAdapter.submitData(requireActivity().getLifecycle(), data);
            }
        });
        dataSubscription = ObjectBoxManager.setLikeUpdateListener(new LikeUpdateListener() {
            @Override
            public void onLikeUpdate(List<FavoriteData> data) {
                if(data.size() == 0){
                   Vb.layoutEmpty.setVisibility(View.VISIBLE);
                }else {
                    Vb.layoutEmpty.setVisibility(View.GONE);
                }
                viewModelLike.update(data);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dataSubscription != null) {
            dataSubscription.cancel();
        }
    }
}