package com.ar.sketch.paint.drawing.frag;

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.sketch.paint.drawing.adapter.ListFavorite;
import com.ar.sketch.paint.drawing.api.OnLike;
import com.ar.sketch.paint.drawing.databinding.FragmentFavoriteBinding;
import com.ar.sketch.paint.drawing.dbmanager.LocalData;
import com.ar.sketch.paint.drawing.dbmanager.MyDataBase;
import com.ar.sketch.paint.drawing.tool.ItemDec;

import java.util.List;

public class PageFavorite extends Fragment {
    private FragmentFavoriteBinding binding;

    public PageFavorite() {

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



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

        return binding.getRoot();
    }

    private void onInit(){
        List<LocalData> datumLocals = MyDataBase.queryAllLike();
        ListFavorite listFavorite = new ListFavorite(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 OnLike() {
            @Override
            public void onAddLike() {
                List<LocalData> datumLocals = MyDataBase.queryAllLike();
                listFavorite.setData(datumLocals);
                updateUi(datumLocals);
            }

            @Override
            public void onDeleteLike() {
                List<LocalData> datumLocals = MyDataBase.queryAllLike();
                listFavorite.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);
        }

    }
}