package com.hd.live.wallpapers.actfrag;

import android.view.View;

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

import com.hd.live.wallpapers.alladapter.AdaLike;
import com.hd.live.wallpapers.base.BaseFragment;
import com.hd.live.wallpapers.bean.FavoriteData;
import com.hd.live.wallpapers.databinding.FragLikeBinding;
import com.hd.live.wallpapers.inter.LikeInterface;
import com.hd.live.wallpapers.others.DbUtils;
import com.hd.live.wallpapers.others.ItemUtils;
import com.hd.live.wallpapers.vm.VmLike;

import java.util.List;

import io.objectbox.reactive.DataSubscription;

public class FragLike extends BaseFragment<FragLikeBinding> {
    private DataSubscription dataSubscription;

    private VmLike vmLike;


    public FragLike() {

    }

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




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

    @Override
    protected void initView() {
        AdaLike likeAdapter = new AdaLike(requireActivity());
        Vb.recycler.setAdapter(likeAdapter);
        Vb.recycler.setLayoutManager(new GridLayoutManager(requireContext(), 2, RecyclerView.VERTICAL, false));
        Vb.recycler.addItemDecoration(new ItemUtils(requireContext(), 8, 8, 8));
        vmLike = getFragmentScopeViewModel(VmLike.class);

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

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