package com.ar.drawing.fragment;

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.adapter.CollectionAdapter;
import com.ar.drawing.listener.OnFavoriteListener;
import com.ar.drawing.ob.DataLocal;
import com.ar.drawing.ob.DbManager;
import com.ar.drawing.databinding.FragmentFavoriteBinding;

import java.util.List;

public class FragmentFavorite extends Fragment {
    private FragmentFavoriteBinding binding;

    public FragmentFavorite() {

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



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

    private void onInit(){
        List<DataLocal> datumLocals = DbManager.queryAllLike();
        CollectionAdapter collectionAdapter = new CollectionAdapter(requireActivity());
        collectionAdapter.setData(datumLocals);
        updateUi(datumLocals);

        binding.recyclerview.setAdapter(collectionAdapter);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(requireContext(), 3));


        DbManager.addListener(new OnFavoriteListener() {
            @Override
            public void onAddLike() {
                List<DataLocal> datumLocals = DbManager.queryAllLike();
                collectionAdapter.setData(datumLocals);
                updateUi(datumLocals);
            }

            @Override
            public void onDeleteLike() {
                List<DataLocal> datumLocals = DbManager.queryAllLike();
                collectionAdapter.setData(datumLocals);
                updateUi(datumLocals);
            }
        });
    }

    private void updateUi(List<DataLocal> 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);
        }

    }
}