package com.study.sketch.learning.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.study.sketch.learning.item.AdapterFavorite;
import com.study.sketch.learning.item.SpacingItemDecoration;
import com.study.sketch.learning.listener.OnFavoriteListener;
import com.study.sketch.learning.database.DataLocal;
import com.study.sketch.learning.database.MyDb;
import com.study.sketch.learning.databinding.FragmentFavoriteBinding;

import java.util.List;

public class FragmentFavorite extends Fragment {
    private FragmentFavoriteBinding binding;

    public FragmentFavorite() {

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



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

        return binding.getRoot();
    }

    private void onInit(){
        List<DataLocal> datumLocals = MyDb.queryAllLike();
        AdapterFavorite adapterFavorite = new AdapterFavorite(requireActivity());
        adapterFavorite.setData(datumLocals);
        updateUi(datumLocals);

        binding.recyclerview.setAdapter(adapterFavorite);
        SpacingItemDecoration spacingItemDecoration = new SpacingItemDecoration(5, true);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(requireContext(), 3));
        binding.recyclerview.addItemDecoration(spacingItemDecoration);

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

            @Override
            public void onDeleteLike() {
                List<DataLocal> datumLocals = MyDb.queryAllLike();
                adapterFavorite.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);
        }

    }
}