package com.cartoon.live.wallpaper.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.live.wallpaper.databinding.FragmentFavoriteBinding;
import com.cartoon.live.wallpaper.listener.OnLikeUpdateApi;
import com.cartoon.live.wallpaper.myadapter.AdapterFavorite;
import com.cartoon.live.wallpaper.mydata.FavoriteData;
import com.cartoon.live.wallpaper.myviewmode.VmLikeFragment;
import com.cartoon.live.wallpaper.parent.BaseFragment;
import com.cartoon.live.wallpaper.utils.Com;
import com.cartoon.live.wallpaper.utils.Db;
import com.cartoon.live.wallpaper.utils.ItemDecoration;

import java.util.List;

import io.objectbox.reactive.DataSubscription;

public class FavoriteFragment extends BaseFragment<FragmentFavoriteBinding> {
    private DataSubscription dataSubscription;

    private VmLikeFragment vmLikeFragment;


    public FavoriteFragment() {

    }

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




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

    @Override
    protected void initView() {
        AdapterFavorite likeAdapter = new AdapterFavorite(requireActivity());
        Vb.recycler.setAdapter(likeAdapter);
        Vb.recycler.setLayoutManager(new GridLayoutManager(requireContext(), 2, RecyclerView.VERTICAL, false));
        Vb.recycler.addItemDecoration(new ItemDecoration(requireContext(), 5, 5, 0));
        vmLikeFragment = getFragmentScopeViewModel(VmLikeFragment.class);

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

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