package com.ar.drawing.assistant.paint.ui_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.assistant.paint.databinding.FragFavoriteBinding;
import com.ar.drawing.assistant.paint.tooladapter.AdFavorite;
import com.ar.drawing.assistant.paint.tooldb.DbManager;
import com.ar.drawing.assistant.paint.tooldb.LocalData;
import com.ar.drawing.assistant.paint.toollistener.OnFavoriteCallback;
import com.ar.drawing.assistant.paint.utils.ItemSpace;

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<LocalData> datumLocals = DbManager.queryAllLike();
        AdFavorite adFavorite = new AdFavorite(requireActivity());
        adFavorite.setData(datumLocals);
        updateUi(datumLocals);
        ItemSpace itemSpace = new ItemSpace(10, 10, 5);
        binding.recyclerview.addItemDecoration(itemSpace);
        binding.recyclerview.setAdapter(adFavorite);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(requireContext(), 3));


        DbManager.addListener(new OnFavoriteCallback() {
            @Override
            public void onAddLike() {
                List<LocalData> datumLocals = DbManager.queryAllLike();
                adFavorite.setData(datumLocals);
                updateUi(datumLocals);
            }

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

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

    }
}