package com.paint.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.paint.ar.drawing.adapter.LikeAdapter;
import com.paint.ar.drawing.api.OnLikeListener;

import com.paint.ar.drawing.databinding.FragmentLikeBinding;
import com.paint.ar.drawing.ob.DataLocal;
import com.paint.ar.drawing.ob.ObManager;

import java.util.List;

public class FragmentLike extends Fragment {
    private FragmentLikeBinding binding;

    public FragmentLike() {

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



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

    private void onInit(){
        List<DataLocal> datumLocals = ObManager.queryAllLike();
        LikeAdapter likeAdapter = new LikeAdapter(requireActivity());
        likeAdapter.setData(datumLocals);
        updateUi(datumLocals);

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


        ObManager.addListener(new OnLikeListener() {
            @Override
            public void onAddLike() {
                List<DataLocal> datumLocals = ObManager.queryAllLike();
                likeAdapter.setData(datumLocals);
                updateUi(datumLocals);
            }

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

    }
}