package com.live.mylivewallpaper.fragment;

import android.os.Bundle;

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.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 io.objectbox.reactive.DataSubscription;

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

    private VmLikeFragment vmLikeFragment;

    public LikeFragment() {

    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


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

    @Override
    protected void initView() {
        LikeAdapter likeAdapter = new LikeAdapter(requireContext());
        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.getPagingData().observe(getViewLifecycleOwner(), resultDataPagingData -> {
            Common.logMsg("---onChanged-------------");
            likeAdapter.submitData(requireActivity().getLifecycle(), resultDataPagingData);
        });
        dataSubscription = Db.setLikeUpdateListener(new OnLikeUpdateListener() {
            @Override
            public void onLikeUpdate() {
                vmLikeFragment.getPagingData().observe(getViewLifecycleOwner(), resultDataPagingData -> {
                    Common.logMsg("---onChanged-2------------");
                    likeAdapter.submitData(requireActivity().getLifecycle(), resultDataPagingData);
                });
            }
        });
    }

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