package com.ar.drawing.art.fragmen;

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

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ar.drawing.art.adapter.adaFavorite;
import com.ar.drawing.art.databinding.FragFavoriteBinding;
import com.ar.drawing.art.dataman.MyBean;
import com.ar.drawing.art.dataman.MyDataBase;
import com.ar.drawing.art.listener.OnLikeListener;
import com.ar.drawing.art.utils.ItemDec;

import java.util.List;

public class FragFavorite extends Fragment {
    private FragFavoriteBinding binding;

    public FragFavorite() {

    }
    public static FragFavorite newInstance() {
        return new FragFavorite();
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragFavoriteBinding.inflate(getLayoutInflater());
        onInit();

        return binding.getRoot();
    }

    private void onInit(){
        List<MyBean> datumLocals = MyDataBase.queryAllLike();
        adaFavorite listFavorite = new adaFavorite(requireActivity());
        listFavorite.setData(datumLocals);
        updateUi(datumLocals);
        ItemDec itemDec = new ItemDec(10, 10, 5);
        binding.recyclerview.addItemDecoration(itemDec);
        binding.recyclerview.setAdapter(listFavorite);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(requireContext(), 3));


        MyDataBase.addListener(new OnLikeListener() {
            @Override
            public void onAddLike() {
                List<MyBean> datumLocals = MyDataBase.queryAllLike();
                listFavorite.setData(datumLocals);
                updateUi(datumLocals);
            }

            @Override
            public void onDeleteLike() {
                List<MyBean> datumLocals = MyDataBase.queryAllLike();
                listFavorite.setData(datumLocals);
                updateUi(datumLocals);
            }
        });
    }

    private void updateUi(List<MyBean> datumLocals){
        if(datumLocals.size()>0){
            binding.recyclerview.setVisibility(View.VISIBLE);
            binding.layoutNoFavorite.setVisibility(View.GONE);
        }else {
            binding.recyclerview.setVisibility(View.GONE);
            binding.layoutNoFavorite.setVisibility(View.VISIBLE);
        }

    }
}