package com.live.mylivewallpaper.fragment;

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

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

import com.live.mylivewallpaper.adapter.LikeAdapter;
import com.live.mylivewallpaper.adapter.MainAdapter;
import com.live.mylivewallpaper.base.BaseFragment;
import com.live.mylivewallpaper.data.LikeData;
import com.live.mylivewallpaper.data.ResultData;
import com.live.mylivewallpaper.databinding.FragmentLikeBinding;
import com.live.mylivewallpaper.databinding.FragmentMainBinding;
import com.live.mylivewallpaper.help.Common;
import com.live.mylivewallpaper.help.Db;
import com.live.mylivewallpaper.help.ItemDecoration;
import com.live.mylivewallpaper.listener.OnLikeUpdateListener;
import com.live.mylivewallpaper.viewmode.VmLikeFragment;

import java.util.List;

import io.objectbox.reactive.DataSubscription;

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

    private VmLikeFragment vmLikeFragment;


    public LikeFragment() {

    }

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




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

    @Override
    protected void initView() {
        LikeAdapter likeAdapter = new LikeAdapter(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<LikeData>>() {
            @Override
            public void onChanged(PagingData<LikeData> data) {
                Common.logMsg("---onChanged-------------");
                likeAdapter.submitData(requireActivity().getLifecycle(), data);
            }
        });
        dataSubscription = Db.setLikeUpdateListener(new OnLikeUpdateListener() {
            @Override
            public void onLikeUpdate(List<LikeData> 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();
        }
    }
}